6

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!

Community
  • 1
  • 1
Masterminder
  • 1,127
  • 7
  • 21
  • 31

2 Answers2

9

A simple way to count the words is by using the >> operator with std::string, like this:

std::stringstream is("There was a farmer named Billy");
std::string word;

int number_of_words = 0;
while (is >> word)
  number_of_words++;

When extracting a std::string from an std::istream the >>operator() will in its default settings skip whitespace which means it will give you each 'word' separated by one or more spaces. So the above code will give you the same result even if the words are separated by more than one space.

mauve
  • 1,976
  • 12
  • 18
9

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).
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380