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");
}
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.
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.
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.
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.