求一个字符的频率
#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 变量中的频率。
注意: 该程序区分大小写,即将同一个字母表的大写和小写版本视为不同的字符。