该任务要求打印出一个输入字符串中所选字符出现的次数(无长度限制)。我想通过仅使用do或do-while循环来解决它,经过一番搜索,我找到了这段代码(来源:https://www.tutorialgateway.org/c-program-to-count-all-occurrence-of-a-character-in-a-string/.)。
我大致明白了它的意思,但还有许多我没有涉及到的东西,比如str[i]的含义、变量ch的含义以及结构的工作方式。我该如何逐个解释它?或者如果有更简单的方法,我该如何处理它?我是一个初学者,我担心这比预期的要容易得多,但我没有继续前进的基础,谢谢。
我大致明白了它的意思,但还有许多我没有涉及到的东西,比如str[i]的含义、变量ch的含义以及结构的工作方式。我该如何逐个解释它?或者如果有更简单的方法,我该如何处理它?我是一个初学者,我担心这比预期的要容易得多,但我没有继续前进的基础,谢谢。
#include <stdio.h>
#include <string.h>
int main() {
char str[10], ch;
int i, Count;
i = Count = 0;
printf("\n Please Enter any String : ");
gets(str);
printf("\n Please Enter the Character that you want to Search for : ");
scanf("%c", &ch);
while (str[i] != '\0') {
if (str[i] == ch) {
Count++;
}
i++;
}
printf("\n The Total Number of times '%c' has Occurred = %d ", ch, Count);
return 0;
}
gets()
函数。它是一个危险的函数。 - codyne