Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of words in a string, C++ [duplicate]

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!

like image 480
Masterminder Avatar asked Oct 13 '12 18:10

Masterminder


People also ask

How do you count repeated words in a string?

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.

How do you count words in a string array?

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.


1 Answers

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.

like image 102
mauve Avatar answered Sep 23 '22 19:09

mauve