我遇到了从数组中对字符串进行排序的问题。我能够对整数进行排序,但我真的不知道如何对字符串从最短到最长进行排序。
我尝试使用 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(Strings, Comparator.comparing(String::length));
这适用于 Java 8 及更高版本。只需确保在文件中的某个位置导入 import java.util.*;
即可。
关于java - 如何按长度对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56265234/