跳到主要内容

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变量中的频率被打印出来。

注意: 这个程序区分大小写,即它将同一个字母的大写和小写版本视为不同的字符。