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!
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:
std::string
reads a word after skiping leading whitespace where a word is a sequence of non-whitespace characters.std::istream_iterator<T>
turns an input stream into a sequence of T
objects by reading corresponding objects until reading fails.std::istringstream
takes a std::string
and turns it into a stream being read from.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.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).