Java – Sorting characters alphabetically in a String

arrayscharjavasortingstring

Could smb please explaing the process of sorting characters of String alphabetically? For example, if I have String "hello" the output should be "ehllo" but my code is doing it wrong.

public static void main(String[] args)
    {
        String result = "";
        Scanner kbd = new Scanner(System.in);
        String input = kbd.nextLine();

        for(int i = 1; i < input.length(); i++)
        {
            if(input.charAt(i-1) < input.charAt(i))
                result += input.charAt(i-1);
            //else 
            //  result += input.charAt(i);
        }
        System.out.println(result);
    }


}

Best Solution

You may do the following thing -

1. Convert your String to char[] array.
2. Using Arrays.sort() sort your char array

Code snippet:

String input = "hello";
char[] charArray = input.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
System.out.println(sortedString);  

Or if you want to sort the array using for loop (for learning purpose) you may use (But I think the first one is best option ) the following code snippet-

input="hello";
char[] charArray = input.toCharArray();
length = charArray.length();

for(int i=0;i<length;i++){
   for(int j=i+1;j<length;j++){
      if (charArray[j] < charArray[i]) {
          char temp = charArray[i];
          charArray[i]=arr[j];
          charArray[j]=temp;
      }
   }
}