C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C 查找字符串中字符出现频率的程序

查找字符串中字符出现频率的C程序

在本例中,您将学习找出字符串中某个字符出现的频率。
要理解此示例,您应该了解以下C 编程 主题:
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 变量中的频率。
注意: 该程序区分大小写,即将同一个字母表的大写和小写版本视为不同的字符。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4