C code to count the number of words in a string

Count the number of words in a string, where a word is defined to be a contiguous sequence of non-space characters.

eg, “Hello, my name is John.” -> 5.

C++:
01 int wordCount(char* s)
02 {
03     int cnt=0;
04     int i=0;
05     bool flag=false;
06     while(true){
07         if(((s[i]>=‘a’)&&(s[i]<=‘z’))||((s[i]>=‘A’)&&(s[i]<=‘Z’))){
08             if(flag==false)
09                 flag=true;
10         }else if(flag==true){
11             cnt++;
12             flag=false;
13         }
14         i++;
15         if(s[i]==){
16             if(flag==true)
17                 cnt++;
18             break;
19         }
20     }
21     return cnt;
22 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s