Counting the number of words in a string, C++

Masterminder picture Masterminder · Oct 13, 2012 · Viewed 10.5k times · Source

Possible Duplicate:
C++ function to count all the words in a string

So I have a line of words which i stored in a string using C++. i.e. "There was a farmer named Billy\n"

I want to know the number of words in the string (i.e. There are currently 6 words in it). Can anyone tell me how to do this? If this is not possible is there a way I can count the number of spaces in the string (i.e. " "). Let me know THanks!

Answer

Dietmar Kühl picture Dietmar Kühl · Oct 13, 2012

Sure, it's simple:

std::cout << "number of words: "
          << std::distance(std::istream_iterator<std::string>(
                               std::istringstream(str) >> std::ws),
                           std::istream_iterator<std::string>()) << '\n';

Just for a bit of explanation:

  1. Reading a std::string reads a word after skiping leading whitespace where a word is a sequence of non-whitespace characters.
  2. std::istream_iterator<T> turns an input stream into a sequence of T objects by reading corresponding objects until reading fails.
  3. std::istringstream takes a std::string and turns it into a stream being read from.
  4. The constructor argument to std::istream_iterator<T> is std::istream&, i.e., the temporary std::istringstream can't be used directly but a reference needs to be obtained. This is the only interesting effect of std::ws which also skips leading whitespace.
  5. std::distance() determines how many elements are in a sequence (the originally used std::count() determines how many elements in the sequence match a given condition but hte condition was actually missing).