用C语言统计某字母在某字符串中出现的次数
时间: 2023-11-11 20:02:33 浏览: 44
您可以使用如下的代码来统计某个字母在一个字符串中出现的次数:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[1000], letter;
int count = 0, i;
printf("请输入字符串: ");
fgets(str, sizeof(str), stdin); // 通过输入流获取字符串
printf("请输入要查找的字母: ");
scanf("%c", &letter);
for (i = 0; i < strlen(str); i++) {
if (str[i] == letter) {
count++;
}
}
printf("字母 %c 在字符串 %s 中出现了 %d 次.\n", letter, str, count);
return 0;
}
```
上述代码中,通过fgets()函数从输入流获取一个字符串,然后从字符串中遍历每个字符,如果字符是要查找的字母,则计数器加1。最后输出字母在字符串中出现的次数。
相关问题
c语言统计字符串中26个字母出现的次数
可以使用数组来统计字符串中每个字母出现的次数,然后遍历输出即可。
以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count[26] = {0}; // 初始化为0
printf("请输入一个字符串:");
gets(str);
// 统计每个字母出现的次数
for (int i = 0; i < strlen(str); i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
count[str[i] - 'a']++;
} else if (str[i] >= 'A' && str[i] <= 'Z') {
count[str[i] - 'A']++;
}
}
// 输出结果
for (int i = 0; i < 26; i++) {
if (count[i] > 0) {
printf("%c:%d\n", i + 'a', count[i]);
}
}
return 0;
}
```
这里使用了 `count` 数组来记录每个字母出现的次数,数组的下标表示字母在字母表中的位置,例如 `count[0]` 表示字母 'a' 出现的次数。遍历字符串时,如果是小写字母,则将对应的 `count` 数组元素加1,如果是大写字母,则将其转换为小写字母后再进行统计。最后遍历 `count` 数组输出结果。
基于c语言使用数据结构统计一个字符串中字母出现的次数
好的,请输入你要统计的字符串:
(输入字符串)
这是一个 C 语言的程序,统计每个英文字母在输入的字符串中出现的次数:
```
#include <stdio.h>
#include <string.h>
void count_letters(char *str);
int main()
{
char str[100];
printf("请输入要统计的字符串:\n");
scanf("%s", str);
count_letters(str);
return 0;
}
void count_letters(char *str)
{
int i, len;
int count[26] = {0};
len = strlen(str);
for (i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
count[str[i]-'a']++;
} else if (str[i] >= 'A' && str[i] <= 'Z') {
count[str[i]-'A']++;
}
}
printf("字母出现次数如下:\n");
for (i = 0; i < 26; i++) {
if (count[i] > 0) {
printf("%c:%d\n", 'a'+i, count[i]);
}
}
}
```
你可以把这段代码复制到你的 C 语言编译器中运行,输入要统计的字符串后,程序就会输出每个英文字母在该字符串中出现的次数。