Reputation: 47
How do I create a String with alphabetical order letters taken from another String?
Let's say I have something like this
String theWord = "Hello";
How do I compute the new String to make it look like"
ehllo
Which is theWord but sorted character by character in alphabetical order.
I came up with this but I am not sure why it isn't working, it just prints out "Hello"
char[] chars = theWord.toCharArray();
Arrays.sort(chars);
String newWord = new String(chars);
System.out.println(newWord);
Upvotes: 0
Views: 77
Reputation: 8946
In sorting first the uppercase letters sort and followed by lowercase letters.
In your example since H is in upper case it comes first suppose you provide the input String as HEllo
then your output will be EHllo
. In addition if your provide input string combination of uppercase,lowercase and numbers, then the sort() method sorts the number first followed by uppercase followed by lowercase.
Example if you provide input string as HEllo397
you will get the output as 379EHllo
So there is nothing wrong with the code.
Upvotes: 0
Reputation: 201429
Yes. Because capital H is before the lower case letters.
String theWord = "hello";
Outputs, as you expected (with no other changes to your code)
ehllo
Upvotes: 2