Word count
Hello
I would like to count how many words are in a string
ie "PETER JOHNSON LTD"
so this string contains 3
I was going to use strtok but this is too slow.
Any other ideas?
sgriffiths
Junior Poster in Training
61 posts since Jun 2006
Reputation Points: 9
Solved Threads: 0
>>Go over the string and count spaces
Generally, yes, but you also have to check if words are separated by more than one white space (spaces or tabs). When a white space character is encountered you have to increment the loop counter until the first non-white space character or end-of-string is found before continuing the loop. If you don't, the word count might be wrong.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Try something like this. It would work for any kind of whitespaces (newline, spaces, tabs).
int main(void)
{
char str[] = " hello \n to all \n\r\f the \t people ";
int limit = strlen(str);
int i, change = 1, words = 0;
for(i = 0; i < limit; ++i)
{
if(!isspace(str[i]))
{
if(change)
{
++words;
change = 0;
}
}
else
{
change = 1;
}
}
printf("Word count: %d\n", words);
getchar();
return(0);
}
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
well, okay...... but we waited almost 3 years for that?
jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
alright, someone close this tard-magnet thread already.
jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179