Java - counts how many words in a String

Description

counts how many words in a String

Demo

public class WordCount {

  public static void main(String args[]) {
    String book = ("Four score and seven years ago, our forefather's brought"
        + " forth on this continent a new nation.");

    char array[] = book.toCharArray(); // transferring String back into characters
    int words = 1; // start by 1 because counting spaces and 1 more word than spaces

    for (int i = 0; i < array.length; i++) {
      if (array[i] == ' ') {
        words++;/* ww w. j  a  v  a 2  s .  c  o  m*/
      }
    }
    
    System.out.println(words);
  }
}

Related Topic