Contents

Sorting strings 1 (with.Java)

   Feb 12, 2024     2 min read

This is an article that looks into the problem of “sorting strings 1”.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

When the string my_string is given as a parameter, write a solution function that selects only the numbers in my_string and returns a list sorted in ascending order.

Restrictions

  • 1 ≤ length of my_string ≤ 100
  • my_string contains one or more numbers.
  • my_string consists of lowercase English letters or numbers from 0 to 9.

Input/Output Example

my_stringresult
“hi12392”[1, 2, 2, 3, 9]
“p2o4i8gj2”[2, 2, 4, 8]
“abcde0”[0]

My solution to the problem

import java.util.*;

class Solution {
     public int[] solution(String my_string) {
         List<Integer> numbers = new ArrayList<>();

         for (char ch : my_string.toCharArray()) {
             if (Character.isDigit(ch)) {
                 numbers.add(Character.getNumericValue(ch));
             }
         }

         Collections.sort(numbers);
         int[] answer = numbers.stream().mapToInt(i -> i).toArray();

         return answer;
     }
}

Solution explanation

solution(String my_string): Extracts numbers from the given string my_string and returns them as a sorted array.

List numbers: List to store numbers.

While iterating through the string, use Character.isDigit(ch) to check whether each character is a number. If it is a number, use Character.getNumericValue(ch) to convert the numeric char to int type and add the number to the list.

Collections.sort(numbers): Sorts the numbers in the list in ascending order.

numbers.stream().mapToInt(i -> i).toArray(): Converts a sorted list to an array.

Code Advantages

Easy to extract and sort numbers: Provides simple code by utilizing Java’s built-in functions and collections to extract and sort numbers.

Code Disadvantages

Number range restriction: The code extracts and sorts only the numbers 0 through 9 from the string.

If you need a different number range, you will need to modify the code.