所以它是c程序中排除特殊字符和数字的字数
int main(){
char str[100];
int i, j = 0;
int len;
char choice;
do {
printf("Enter String: ");
fgets(str, sizeof(str), stdin);
len = strlen(str);
for (i = 0; i < len; i++) {
if((str[i] >= 'A' && str[i] <= 'Z') ||
(str[i] >= 'a' && str[i] <= 'z')) //checks if its upper or lowercase {
if (str[i] != ' ' && (str[i + 1] == ' ' || str[i + 1] == '\0'))//checks if the current character is a space and also the end of the string{
j++;
}
}
}
printf("Word count: %d\n", j);
printf ("Try again?(Y/N): ");
scanf (" %c", &choice);
getchar ();//use to clear input buffer
} while (choice == 'y' || choice == 'Y');
return 0;
}
但它不计算空格后的第一个字符串,并且当我继续循环时似乎有点混乱。
我尝试更改数组、循环的值,也尝试询问人工智能我错过了什么,但这些建议并没有真正起作用。
对于初学者来说,函数 fgets 可以附加换行符 ' ' 到输入的字符串。
您应该删除它或在 if 语句中考虑它。
其次,您不会在 do-while 循环中将变量 j 重置为零。
此外,使用标准函数 isalpha 而不是将字符与符号进行比较会更好。
tab
字符 ' ' alco 也可以分隔单词。