用c语言统计某个字符在目标字符串中出现的次数 输入
时间: 2023-05-24 17:04:40 浏览: 52
可以按照以下代码实现:
```c
#include <stdio.h>
#include <string.h>
int count_char(char *str, char c)
{
int count = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == c) {
count++;
}
}
return count;
}
int main()
{
char str[100];
char c;
int count;
printf("Please enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Please enter a character: ");
scanf("%c", &c);
count = count_char(str, c);
printf("The character '%c' appears %d times in the string.\n", c, count);
return 0;
}
```
输入一个字符串和一个字符,然后调用 `count_char` 函数进行统计。该函数遍历字符串中每个字符,如果字符与目标字符匹配,则计数器加 1。最后返回计数器的值。
注意,如果要输入含有空格的字符串,需要使用 `fgets` 函数。而在输入字符时,可以使用 `scanf` 函数,但要注意输入后需要清除缓存区中的 `\n` 符号。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)