我正在尝试按字母顺序对字符串中的字符进行排序,当我使用以下示例运行我的代码时:hello
,然后我得到:heeeeeeeeeheeeelheeellhee
而不是 ehllo
。 smb 可以建议我应该在我的代码中修复什么吗?提前致谢!
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);
}
最佳答案
为什么这么复杂?
public String sortByChar(String s)
{
char[] cs = s.toCharArray();
Arrays.sort(cs);
return new String(cs);
}
关于java - 对 String 中的字符进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30227460/