Counting words in an array

Hey guys, I'm at a loss here. I have an array named comments[] and it holds 93 different YouTube comments. I've been trying to figure out how I can count how many words are in each comment. I thought something like my code below would work, but it just keeps adding to the word count way past what it should be. I don't know if this is enough of my code to be helpful. I don't understand why it keeps running the if statement.

1
2
3
4
5
6
7
8
9
10
11
  for (int k = 0; k <= comments[j].length(); k++)
		{
			if (comments[j].find(' ') != string::npos)
			{
				wordCount++;
				cout << endl << "\nThe word count is: " << wordCount << " for comment: " << comments[j] << endl;
			}

			 //cout << endl << "\nThe word count is: " << wordCount << " for comment: " << comments[j] << endl;
			 system("Pause");
		}
C++ can do this for you. Count the number of spaces and add 1:
http://www.cplusplus.com/reference/algorithm/count/

1
2
unsigned words = 1 + std::count(comments[j].first(), comments[j].last(), ' '); //I was tired
unsigned words = 1 + std::count(comments[j].begin(), comments[j].end(), ' ');


For future reference, the reason your code did not work was because you always tried to find from the beginning of the string. Instead you need to find from after your last result.
Last edited on
Wow I can't believe it's that easy. Thank you very much.

A quick side note: I had to use begin and end instead of first and last in that line of code you gave me.
Oops! That was a typo, woah. I am tired today.
Last edited on
What about the case where a string has multiple spaces in a row? People sometimes put double spaces when starting a new sentence, or tabs or other white space characters. Maybe a regex to preprocess the string before using the count+1 technique.
If you're going to use regex you can throw out the count+1 technique completely and just take the number of regex matches plus 1.
There doesn't happen to be a function that lets you find the longest word is there? I just want to make sure there isn't before I start digging into this.
If you split all the words into a vector and then sort the vector, well, I think you know how alphabetical order works.

http://stackoverflow.com/q/236129/1959975 (see the second answer - the first is if you're reading from an input stream)
Last edited on
I have not learned about vectors yet so I don't I think I can use them for this assignment.
Oh, but you learned about std::count before this assignment? Probably not - if you're worried about it you can ask your professor if you're allowed to use things that have not been taught in class. In the worst case you can go back to your original attempt and fix it like I recommended and then just keep track of the highest difference between two spaces and the word between them.
Topic archived. No new replies allowed.