【发布时间】:2019-05-22 21:26:39
【问题描述】:
我遇到了从数组中排序字符串的问题。我能够对整数进行排序,但我真的不知道如何将字符串从最短到最长排序。
我尝试使用 Strings.length 将字符串转换为整数,但我不知道如何将它们转换回原来的字符串。
字符串处理程序;
System.out.println("\nNow we will sort String arrays.");
System.out.println("\nHow many words would you like to be sorted.");
Input = in.nextInt();
int Inputa = Input;
String[] Strings = new String [Input];
for (int a = 1; a <= Input; Input --) //will run however many times the user inputed it will
{
counter ++; //counter counts up
System.out.println("Number " + counter + ": "); //display
userinputString = in.next();
Strings[countera] = userinputString; //adds input to array
countera ++;
}
System.out.println("\nThe words you inputed are :");
System.out.println(Arrays.toString(Strings));
System.out.println("\nFrom shortest to longest the words are:");
counter = 0;
int[] String = new int [Strings.length];
for (int i = 0; i < Strings.length; i++) //will run however many times the user inputed it will
{
int a = Strings[i].length();
String[i] = a;
}
System.out.println(Arrays.toString(String));
我希望能够对实际的字符串进行排序,但是我得到了数字并且无法找到如何在排序后将这些数字转回它们的字符串。
【问题讨论】:
-
“从最短到最长”与“按字母顺序”不同。你可以使用库函数吗?
-
要从最短到最长排序(反之亦然),您需要实现一个比较器,它将定义一个字符串何时“大于”另一个
-
将第二个参数传递给
Arrays.sort,它将是Comparator<String>的匿名实现类实例。在其compare方法中,返回new Integer(str1.length()).compareTo(str2.length()) -
@chrylis: brainyquote.com/quotes/casey_stengel_125597 ;-)
标签: java arrays string sorting