Search code examples
javastringsentence

How to divide a sentence into parts Java?


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?


Solution

  • 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]);