如何使用gets()
或fgets()
来计算字长并输出它们的出现?例如,这里是代码这样做,但使用下面的getchar()
。我认为在gets()
中编写它可以更容易地将所有分隔符合并到程序中,而不是必须手动设置每个分隔符的语句吗?C编程:计算字符串中出现的字长
#include <string.h>
#include <ctype.h>
const char delim[] = ", . - !*()&^%$#@<> ? []{}\\/\"";
#define SIZE 100
int main(void){
int length[SIZE] = { 0 };
int name[SIZE];
int i = 0, ch, word_len = 0;
int count = 0;
printf("enter sentence: ");
while (1){
ch = getchar();
if (isalpha(ch)){
++word_len;
}
else if (ch == ' ' || ch == '.'){
if (word_len)
length[word_len - 1]++;//-1: to 0 origin
if (ch == '.')
break;
word_len = 0;
}
}
printf("Word Length \tCount \n");
for (i = 0; i<sizeof(length)/sizeof(*length); ++i){
if (length[i])
printf(" %d \t\t%d\n", i + 1, length[i]);
}
return 0;
}
'else if(strchr(delim,ch)){'可能满足需要。 (替换'else if(ch ==''ch =='。'){' – chux