How to divide a sentence into parts Java?

cchua picture cchua · Jun 19, 2012 · Viewed 14.9k times · Source

How can I divide a sentence like "He and his brother playing football." into few part like "He and", "and his", "his brother", "brother playing" and "playing football" . Is it possible to do that by using Java?

Answer

st0le picture st0le · Jun 19, 2012

Assuming the "words" are always separated by a single space. Use String.split()

String[] words = "He and his brother playing football.".split("\\s+");
for (int i = 0, l = words.length; i + 1 < l; i++)
        System.out.println(words[i] + " " + words[i + 1]);