查找字符串中字符出现频率的 C 程序
在此示例中,您将学习查找字符串中某个字符的频率。
要理解此示例,您应该具备以下 C 语言编程主题的知识:
查找字符的频率
#include <stdio.h>
int main() {
char str[1000], ch;
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter a character to find its frequency: ");
scanf("%c", &ch);
for (int i = 0; str[i] != '\0'; ++i) {
if (ch == str[i])
++count;
}
printf("Frequency of %c = %d", ch, count);
return 0;
}
输出
Enter a string: This website is awesome.
Enter a character to find its frequency: e
Frequency of e = 4
在这个程序中,用户输入的字符串存储在 str
中.
然后,要求用户输入要查找其频率的字符。这存储在变量 ch
中.
然后,使用 for
循环遍历字符串的字符。在每次迭代中,如果字符串中的字符等于 ch
, count
增加 1。
最后,频率存储在 count
变量被打印到屏幕上。