#include <stdio.h>
#include <string.h>

int main()
{
    char str[100];
    char ch;
    int count = 0;
    printf("请输入字符串:");
    fgets(str, 100, stdin);
    printf("请输入要查找的字符:");
    scanf(" %c", &ch);
    
    for(int i = 0; i < strlen(str); i++)
    {
        if(str[i] == ch)
        {
            count++;
        }
    }
    
    printf("字符串中' %c '的个数为%d\n", ch, count);
    return 0;
}

说明:

  • 使用fgets()函数可以读取包含空格的字符串,因为它会读取一整行。
  • 使用scanf()函数输入字符时,需要在前面加一个空格,避免读取上一个输入中的回车字符。
C语言统计字符串中特定字符的个数 - 代码示例

原文地址: https://www.cveoy.top/t/topic/oq64 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录