I'm trying to sort the characters alphabetically in a String and when I run my code with the following example: hello, then I get: heeeeeeeeeheeeelheeellhee instead of ehllo. Could smb suggest me what I should fix in my code? Thanks in advance!
public static void main(String[] args)
{
String result = "";
Scanner kbd = new Scanner(System.in);
String input = kbd.nextLine();
char[] myArray = input.toCharArray();
for(int i = 0; i < myArray.length; i++)
for(int j = 0; j < myArray.length; j++)
{
if(myArray[i] > myArray[j])
{
char temp = myArray[j];
myArray[j] = myArray[i];
myArray[i] = temp;
result += myArray[i];
}
else
result += myArray[i];
}
System.out.println(result);
}
Why so complicated?
public String sortByChar(String s)
{
char[] cs = s.toCharArray();
Arrays.sort(cs);
return new String(cs);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With