搜索此博客

2013年2月12日星期二

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
Hint: Take account for extra spaces at the start and end of the string, and there might be more than multiple spaces between words.

C语言: CountNumOfWords
01 int countNumWords(char *str)
02 {
03     char *p=str;
04     if(*p=='\0')
05     {
06         return 0;
07     }
08     int len=strlen(str);
09     char *q=p+len-1;
10     int count=1;
11     while(*p==' ') p++;
12     while(*q==' ') q--;
13     if(p>=q)
14         return 0;
15     while(p<q && *p!='\0')
16     {
17         p++;
18         if(*p==' ')
19         {
20            while(*p==' ')
21            {
22                p++;
23            }
24            count++;
25         }
26     }
27     return count;
28 }

没有评论:

发表评论