Take the 2-minute tour ×

I need the user to enter a string and give back the first word in lexicographic order. I was thinking of using the string compare function, but I have the whole line as a single string. For example, I have a String containing "4 WAIT WHAT IS THIS"; the output would be "IS", as it is the lexicographically smallest word. How can I extract one word from the string?

share|improve this question
Have you tried anything? –  juergen d Sep 8 '12 at 1:54
add comment

1 Answer

As this is homework, I'll provide you with the general approach. You'll need to analyze the String, likely by splitting it into its individual words, and finding the length on each.

Sure, you probably could use a "sort" to do this - by storing each word along with its size as part of a collection with a custom comparator. However, for the sake of your assignment, you'd probably be best advised to simply run this as part of a loop - keeping track of the minimum size, then comparing each following word and seeing if you find a new smallest size, then returning the smallest found.

share|improve this answer
add comment

Your Answer


