C语言输入一个字符串和一个字符,统计该字符在字符串中出现的次数
时间: 2023-11-14 19:05:44 浏览: 66
```
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], ch;
int i, count = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
printf("请输入一个字符:");
scanf("%c", &ch);
for(i = 0; i < strlen(str); i++)
{
if(str[i] == ch)
{
count++;
}
}
printf("%c在%s中出现了%d次。\n", ch, str, count);
return 0;
}
```
相关问题
C语言输入一个字符串统计各个字符出现次数
以下是C语言代码示例:
```
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char str[MAX_LEN], freq[256] = {0};
int len, i;
printf("Enter a string: ");
fgets(str, MAX_LEN, stdin);
len = strlen(str);
for (i = 0; i < len; i++) {
freq[str[i]]++;
}
printf("Character frequency:\n");
for (i = 0; i < 256; i++) {
if (freq[i] != 0) {
printf("%c: %d\n", i, freq[i]);
}
}
return 0;
}
```
这段代码首先定义了一个字符串 `str` 和一个长度为 256 的数组 `freq`,用于存储每个字符出现的次数。
然后通过 `fgets` 函数从标准输入中读取字符串,并计算字符串长度。
接下来通过循环遍历字符串中的每个字符,将其在 `freq` 数组中对应的位置上加一。
最后再次循环遍历 `freq` 数组,输出每个字符出现的次数。
c语言 输入一个字符串,统计其中某个字符出现的次数。
你好!好的,你的问题是如何输入一个字符串并统计其中某个字符出现的次数。以下是一个简单的例子:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[1000], ch;
int count = 0, i;
printf("请输入一个字符串:");
gets(str); // 输入字符串
printf("请输入要统计的字符:");
scanf("%c", &ch); // 输入要统计的字符
for (i = 0; i < strlen(str); i++) { // 遍历字符串
if (str[i] == ch) { // 如果当前字符和要统计的字符相同
count++; // 计数器加1
}
}
printf("%c在字符串中出现了%d次。\n", ch, count); // 输出统计结果
return 0;
}
```
在这个例子中,首先我们定义了一个字符串变量 `str` 和一个字符变量 `ch`,以及一个计数器 `count`,用于统计字符出现的次数。我们首先通过 `gets()` 函数输入一个字符串,然后通过 `scanf()` 函数输入一个字符,接着使用 `strlen()` 函数获取字符串长度,使用 for 循环遍历字符串,判断当前字符是否和要统计的字符相同,如果相同则计数器加1。最后我们输出统计结果。
相关推荐
![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)