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!
Approach: First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.
Instantiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array. Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With