Use a StringTokenizer
to tokenize the sentence and fill the words in a list.
A StringTokenizer
object uses the characters " \t\n\r\f"
(the space character, the tab character, the newline character, the carriage-return character, and the form-feed character) by default as delimiters to split the sentence into tokens.
Then call Collections#sort(List, Comparator)
with a case-insensitive comparator.
String sentence = "Big Bang Theory is better than Two and a Half Men";
StringTokenizer tokenizer = new StringTokenizer(sentence);
List<String> words = new ArrayList<String>();
while(tokenizer.hasMoreTokens()) {
words.add(tokenizer.nextToken());
}
Collections.sort(words, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
In the above code, a custom comparator is added to use String.compareToIgnoreCase
to ignore case when comparing two strings. If you don't provide a custom comparator, you would end up with a list of words sorted as Bang, Big, Half, Men, Theory, Two, a, and, better, is, than
.
Read the Javadocs of the relevant classes:
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
Javadoc for Collections.sort
:
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)