用c语言写一个统计字母出现次数的函数
时间: 2023-11-09 07:07:55 浏览: 37
以下是一个用C语言编写的统计字母出现次数的函数:
```c
void count_letters(char* str, int* counts) {
int i, index;
char ch;
// 初始化计数器数组
for (i = 0; i < 26; i++) {
counts[i] = 0;
}
// 遍历字符串
for (i = 0; str[i] != '\0'; i++) {
ch = str[i];
// 将大写字母转换为小写字母
if (ch >= 'A' && ch <= 'Z') {
ch += 'a' - 'A';
}
// 忽略非字母字符
if (ch < 'a' || ch > 'z') {
continue;
}
// 计算字符索引
index = ch - 'a';
// 增加计数器
counts[index]++;
}
}
```
这个函数接受一个指向字符串的指针和一个整型数组作为参数。它将字符串中每个字母出现的次数保存在计数器数组中。注意,这个函数只会计算字母,忽略字符串中的非字母字符。
相关问题
c语言使用函数统计26个字母出现的次数
可以使用一个数组来存储每个字母出现的次数,然后遍历字符串,对应的字母出现次数加1。最后输出数组中每个元素的值即可。
具体实现如下:
```c
#include <stdio.h>
#include <string.h>
void count_letters(char *str, int *count) {
int len = strlen(str);
for (int 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']++;
}
}
}
int main() {
char str[100];
int count[26] = {0};
printf("请输入字符串:");
scanf("%s", str);
count_letters(str, count);
for (int i = 0; i < 26; i++) {
printf("%c出现了%d次\n", 'a' + i, count[i]);
}
return 0;
}
```
这个程序首先定义了一个`count_letters`函数,用来统计字母出现的次数。这个函数接受两个参数,一个是字符串指针,一个是整型数组指针。在函数内部,首先获取字符串的长度,然后遍历字符串,如果当前字符是小写字母,则将对应的计数器加1;如果当前字符是大写字母,则将对应的计数器加1。最后,函数返回时,整型数组中存储的就是每个字母出现的次数。
在主函数中,首先定义了一个长度为26的整型数组,用来存储每个字母出现的次数。然后,程序提示用户输入一个字符串,调用`count_letters`函数统计字母出现的次数。最后,程序遍历整型数组,输出每个字母出现的次数。
用C语言写一个函数用来统计字符串中各字母出现的次数
以下是一个用C语言写的函数,可以统计字符串中各字母出现的次数:
```c
#include <stdio.h>
void countLetters(char* str) {
int count[26] = {0}; // 初始化计数数组
int i = 0;
while (str[i] != '\0') { // 遍历字符串
if (str[i] >= 'a' && str[i] <= 'z') { // 判断是否为小写字母
count[str[i] - 'a']++; // 对应字母计数器加一
} else if (str[i] >= 'A' && str[i] <= 'Z') { // 判断是否为大写字母
count[str[i] - 'A']++; // 对应字母计数器加一
}
i++;
}
for (i = 0; i < 26; i++) { // 输出各字母计数结果
printf("%c: %d\n", 'a' + i, count[i]);
}
}
int main() {
char str[] = "Hello, world!";
countLetters(str);
return 0;
}
```
该函数使用一个长度为26的计数数组来统计各字母出现的次数。在遍历字符串时,如果遇到小写字母,则将计数数组的对应元素加一;如果遇到大写字母,则同样将计数数组的对应元素加一。最后,使用一个循环输出各字母的计数结果。
对于字符串 "Hello, world!",该函数的输出结果为:
```
a: 0
b: 0
c: 0
d: 1
e: 1
f: 0
g: 0
h: 1
i: 0
j: 0
k: 0
l: 3
m: 0
n: 0
o: 2
p: 0
q: 0
r: 1
s: 0
t: 0
u: 0
v: 0
w: 1
x: 0
y: 0
z: 0
```