Monday, December 29, 2008

Count number of word ( C )

Word in my definition is sequence of non-space character.
Count number of word in sentence was an easy task if you already know the trick.

Example:

My name is Timo ==> counted as four word
I like to solve problems ==> counted as five word


So to create a computer program that count number of word, we can count based on how many space that separate the word (trailing space will be counted once).



int count(char sentence[]) {
int i;
int ret = 0;
int x = 0;
for(i=0;sentence[i];i++)
{
if(sentence[i]!=' ')
{
x = 1;
}
else
{
ret += x;
x = 0;
}
}
return ret + x;
}


Hope this tutorial will be useful :D.

No comments:

Post a Comment