Thursday, October 11, 2012

Count the number of words in a string


Count the number of words in a string, where a word is defined to be a contiguous sequence of non-space characters.

eg, “Hello, my name is John.” -> 5

Strategy:

The key is to note when it is in a word and when it is not; When it changes from not-in-word to in-word, increment wordCount by one.

int countNumWords(const char *str) {
  bool inWord = false;
  int wordCount = 0;
  while (*str) {
    if (!inWord && isalpha(*str)) {
      inWord = true;
      wordCount++;
    }
    else if (inWord && *str == ' ') {
      inWord = false;
    }
    str++;
  }
  return wordCount;
}

1 comment: