ErikBurney
ErikBurney

Reputation: 3

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.

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.

Upvotes: 0

Views: 2800

Answers (2)

KoreanwGlasses
KoreanwGlasses

Reputation: 284

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. Just make sure you import import java.util.*; at some point in your file.

Upvotes: 4

colos_enough
colos_enough

Reputation: 181

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. You can also do this in a lambda comparator passed to the Arrays.sort().

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

Upvotes: 0

Related Questions