简体   繁体   English

如何按长度对字符串排序

[英]How to sort strings by length

I have run into a problem of sorting strings from an Array. 我遇到了对数组中的字符串进行排序的问题。 I was able to sort integers, but I don't really know how to sort the Strings from shortest to longest. 我能够对整数进行排序,但是我真的不知道如何将字符串从最短到最长排序。

I have tried converting the Strings into integers by using Strings.length but I don't know how to convert them back into their original String. 我尝试使用Strings.length将Strings转换为整数,但是我不知道如何将其转换回其原始String。

String Handler; 字符串处理程序;

        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));

I expected to be able to have the actual String to sort but the I'm getting numbers and am unable to find how to turn those numbers back into their string after sorting. 我希望能够对实际的String进行排序,但是我正在获取数字,并且无法找到如何在排序后将这些数字转换回其字符串。

If you're allowed to use library functions, then you might want to do the following: 如果允许使用库函数,则可能需要执行以下操作:

Arrays.sort(Strings, Comparator.comparing(String::length));

this works in Java 8 and above. 这适用于Java 8及更高版本。 Just make sure you import import java.util.*; 只需确保导入import java.util.*; at some point in your file. 在文件中的某个位置。

It is not possible to convert them as you store only the length - there might be many different strings with same length. 由于仅存储长度,因此无法转换它们-可能有许多长度相同的不同字符串。 Instead of this you can try to implement your own comparator and pass it to java's sort methods: given two strings returns 1 if first is longer, 0 if equal, -1 if shorter. 取而代之的是,您可以尝试实现自己的比较器并将其传递给java的sort方法:如果第一个字符串较长,则给定两个字符串,如果相等则返回0,如果相等则返回-1。 You can also do this in a lambda comparator passed to the Arrays.sort(). 您也可以在传递给Arrays.sort()的lambda比较器中执行此操作。

(s1, s2) -> {
      if (s1.length() < s2.length()) {
           return -1;
      }
      return s1.length() > s2.length();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM