问题描述
我想排序字符串使用的compareTo()的数组。这是我的code:
I am trying to sort an array of Strings using compareTo(). This is my code:
static String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String temp;
public static void main(String[] args)
{
for(int j=0; j<Array.length;j++)
{
for (int i=j+1 ; i<Array.length; i++)
{
if(Array[i].compareTo(Array[j])<0)
{
String temp= Array[j];
Array[j]= Array[i];
Array[i]=temp;
}
}
System.out.print(Array[j]);
}
}
现在的输出:您好本例排序是
now output is : Hello This Example Sorting is
我收到了一些成绩,但不是我想要得到的,我的逻辑是正确的有啥错在这里,任何人都可以帮助我吗?
I am getting some result but not the one i want to get , for me logic is right so whats wrong here , anyone can help me please?
推荐答案
您的输出是正确的。表示你好和本开头的白色字符。
Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.
另一个问题是与你的方法,你为什么不使用 Arrays.sort()
方法?
Another issue is with your methodology, why don't you use Arrays.sort()
method?
String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);
数组这里第三个元素是应为是,否则它会持续排序后进来了。因为排序方法内部使用ASCII值元素进行排序。
Here third element of array "is" should be "Is" otherwise it will come in last after sorting. Because sort method internally uses ASCII value to sort elements.
这篇关于排序字符串与Java数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!