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.