Contents

Sorting strings 2 (with.Java)

   Apr 23, 2024     2 min read

This is an article about the problem of “Sort strings 2 (with.Java)”.

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 a string my_string consisting of upper and lower case English letters is given as a parameter, complete the solution function to change my_string to all lowercase letters and return a string sorted in alphabetical order.

Restrictions

  • 0 < my_string < 100

Input/Output Example

my_stringresult
“Bcad”“abcd”
“heLLo”“ehllo”
“Python”“hnopty”

My solution to the problem

import java.util.Arrays;

class Solution {
     public String solution(String my_string) {
         String answer = my_string.toLowerCase();

         char[] chars = answer.toCharArray();
         Arrays.sort(chars);
         answer = new String(chars);
         return answer;
     }
}

Solution explanation

  • Lowercase conversion: Converts the given string to lowercase using the toLowerCase method.
  • Convert to and sort a character array: Use the toCharArray method to convert a string to a character array, and use the Arrays.sort method to sort the character array alphabetically.
  • Convert to string: Convert the sorted character array back to a string and save it in the answer.
  • Return result: Returns the final sorted string.

Code Advantages

  • Simple string sorting: You can easily convert and sort strings to lowercase by utilizing Java’s built-in methods.
  • Code conciseness: Strings are handled in a simple yet effective way.

Code Disadvantages

  • No handling of Unicode characters: The current code performs sorting on ASCII characters. To properly handle Unicode characters, you need to consider another approach.
  • Ignoring string immutability: Since strings are immutable, the process of converting a sorted character array back to a string may seem unnecessary. This part can be optimized.
  • No exception handling when the string is null: The current code does not consider handling when the given string is null. I recommend adding exception handling for null.
  • No handling if string contains spaces: The current code sorts without considering spaces within the string. If you want to include spaces in the sorting, you need to modify that part.