It is necessary to sort the array of strings by the number of words in each element of the array, from the smallest to the largest. For example, there is such an array:

{ "hello my world", "Hello world", "Hello", "Hello world this is me" }; 

After sorting should be:

 { "Hello", "Hello world", "hello my world", }; 

But it turns out not exactly what you need:

  String[] stringArray = { "hello my world", "Hello world", "Hello", "Hello world this is me", "Hello world this is me and you" }; for (int i = 0; i < stringArray.length; i++) { for (int j = i + 1; j < stringArray.length; j++) { StringTokenizer sTokenizer = new StringTokenizer(stringArray[i]); int tokens = sTokenizer.countTokens(); if (stringArray[j].compareTo(stringArray[i]) < tokens) { String temp = stringArray[j]; stringArray[j]=stringArray[i]; stringArray[i]=temp; } } System.out.println(stringArray[i]); } 

I count the number of words in each line and then swap the elements.

    2 answers 2

    Omit until the question of efficiency, you do

     StringTokenizer sTokenizer = new StringTokenizer(stringArray[i]); int tokens = sTokenizer.countTokens(); 

    You have received the number of words in the i element of the array. Then you do

     if (stringArray[j].compareTo(stringArray[i]) < tokens 

    Already looks to say the least strange.

    Write like this

     StringTokenizer sTokenizerL = new StringTokenizer(stringArray[i]); int tokensL = sTokenizerL.countTokens(); StringTokenizer sTokenizerR = new StringTokenizer(stringArray[j]); int tokensR = sTokenizerR.countTokens(); if ( tokensL < tokensR) //swap 

    But the implementation is extremely inefficient. I'd rather do something like this

     class Pair implements Comparable { public int tokenCount; public String string; public Pair(String string){ this.string = string; StringTokenizer sTokenizer = new StringTokenizer(string); tokenCount = sTokenizer.countTokens(); } public int compareTo(Object obj){ Pair other = (Pair)obj; return tokenCount - other.tokenCount; } public String toString(){ return string; } } 

    And use it to sort through the standard Arrays.sort method Arrays.sort

    • Thank! @pavel - Nevada 2:22 pm

    Not the best solution, but the shortest

      Arrays .stream(array) .sorted((c1, c2) -> Integer.compare(c1.split("\\s").length, c2.split("\\s").length)) .forEach(System.out::println);