用c语言实现统计字符串中出现的字符及次数
时间: 2023-11-16 08:05:49 浏览: 39
好的,这个问题可以回答。以下是C语言的代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int freq[256] = {0};
int i;
printf("请输入字符串:");
gets(str);
for(i=0; i<strlen(str); i++) {
freq[str[i]]++;
}
for(i=0; i<256; i++) {
if(freq[i] != 0) {
printf("字符 '%c' 出现了 %d 次\n", i, freq[i]);
}
}
return 0;
}
```
这段代码可以统计字符串中每个字符出现的次数。其中,freq数组用来记录每个字符出现的次数,它的下标是字符的ASCII码。使用gets()函数可以获取用户输入的字符串。最后,将freq数组中不为0的元素输出即可。
相关问题
C语言实现统计字符串中各字母的个数的算法思想
要统计字符串中各字母的个数,可以使用以下算法思想:
1. 首先,定义一个大小为26的整型数组 `count`,用于记录每个字母的个数。数组的下标表示字母的ASCII码减去字母 'a' 的ASCII码,即 `[0]` 对应字母 'a',`[1]` 对应字母 'b',以此类推。
2. 初始化数组 `count` 中的所有元素为0。
3. 使用循环遍历字符串中的每个字符。
4. 在每次循环中,判断当前字符是否是字母。如果是,则将其转换为小写字母,并计算其在数组 `count` 中的下标。
5. 使用下标访问数组 `count`,并将对应位置的值加1,表示该字母出现的次数加1。
6. 重复步骤3-5,直到处理完整个字符串。
7. 遍历数组 `count`,输出每个字母及其对应的个数。
通过这个算法思想,可以统计字符串中各字母的个数并输出结果。
c语言,统计字符串s在字符串str中出现的次数。
可以使用字符串匹配的方法来统计字符串s在字符串str中出现的次数。以下是一个基于C语言的例子:
```c
#include <stdio.h>
#include <string.h>
// 统计字符串s在字符串str中出现的次数
int countOccurrences(char *str, char *s)
{
int count = 0;
int len = strlen(s);
while (*str)
{
if (strncmp(str, s, len) == 0)
{
count++;
str += len; // 将指针移动到下一个可能的匹配位置
}
else
{
str++;
}
}
return count;
}
int main()
{
char str[] = "hello, world! hello, hello";
char s[] = "hello";
int count = countOccurrences(str, s);
printf("'%s' occurs %d times in '%s'\n", s, count, str);
return 0;
}
```
输出结果为:
```
'hello' occurs 3 times in 'hello, world! hello, hello'
```