如果给出以下的char散文:
“希望是有羽毛的东西 在灵魂中栖息 并且在没有单词的情况下唱出曲调 永远不会停止“
如何计算字符串的长度和空格数?以下是我到目前为止的情况:
#include <stdio.h>
#include <ctype.h>
int count(char *string);
int main(void){
char prose[ ] =
"Hope is the thing with white feathers\n"
"That perches in the soul.\n"
"And sings the tne without the words\n"
"And never stops at all.";
printf("count of word : %d\n", count(&prose[0]));
return 0;
}
char *NextWordTop(char *string){
static char *p = NULL;
char *ret;
if(string)
p = string;
else if(!p)
return NULL;
while(isspace(*p))++p;
if(*p){
ret = p;
while(!isspace(*p))++p;
} else
ret = p = NULL;
return ret;
}
int count(char *str){
int c = 0;
char *p;
for(p=NextWordTop(str); p ; p=NextWordTop(NULL))
++c;
return c;
}
答案 0 :(得分:1)
#include <stdio.h>
#include <ctype.h>
int main(void){
char prose[ ] =
"Hope is the thing with white feathers\n"
"That perches in the soul.\n"
"And sings the tne without the words\n"
"And never stops at all.";
int len, spc;
char *p = prose;
for(len=spc=0;*p;++p){
++len;
if(isspace(*p))//if(' ' == *p)
++spc;
}
printf("length : %d\t spaces : %d\n", len, spc);
//length : 123 spaces : 23
return 0;
}