eg,
Hint: Take account for extra spaces at the start and end of the string, and there might be more than multiple spaces between words."Hello, my name is John." -> 5
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 }
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 }
没有评论:
发表评论