Eric
Eric

Reputation: 175

Sorting the words in a string lexicographically

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?

Upvotes: 0

Views: 478

Answers (1)

ziesemer
ziesemer

Reputation: 28697

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.

Upvotes: 1

Related Questions