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