java如何按长度对字符串排序
我遇到了从数组中排序字符串的问题。我能够对整数进行排序,但我真的不知道如何将字符串从最短到最长排序
我尝试过使用字符串将字符串转换成整数。长度,但我不知道如何将它们转换回原始字符串
字符串处理程序
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));
我希望能够有实际的字符串进行排序,但我得到的是数字,无法找到如何在排序后将这些数字转换回字符串
# 1 楼答案
如果允许使用库函数,则可能需要执行以下操作:
这在Java8及更高版本中有效。只需确保在文件中的某个位置导入
import java.util.*;
# 2 楼答案
由于只存储长度,因此无法转换它们——可能有许多不同的字符串具有相同的长度。 相反,您可以尝试实现自己的比较器,并将其传递给java的排序方法:给定两个字符串,如果第一个更长,则返回1,如果相等,则返回0,如果更短,则返回1。也可以在传递给数组的lambda比较器中执行此操作。排序()