题目:统计字符串中每个英文字符出现的个数,不区分大小写
思路:
- 控制台任意输入字符串,进行判断每个字符个数
- 首先判断是否是英文字符(使用头文件<ctype.h>中的isalpha),再转换为小写
参考链接:https://zh.cppreference.com/w/c/string/byte
3.每个英文字符都有对应ASCII码值,使用查表方法解决
代码展示:
#include <stdio.h>
#include<ctype.h>
#define LETSIZE 26
int main(){
int let[LETSIZE] = {};
char ch;
while ((ch = getchar()) != '\n')
{
if (isalpha(ch))//判读是否是英文字符
{
ch = tolower(ch);//转化为小写
let[ch - 'a'] += 1;
}
}
for (int i = 0; i < LETSIZE; ++i)
{
printf("%c=>%d\n", i + 'a', let[i]);
}
return 0;
}
示例输出:
如果区分大小写
代码展示:
#include <stdio.h>
#include<ctype.h>
#define LETSIZE 26
int main(){
int letlow[LETSIZE] = {};
int letup[LETSIZE] = {};
char ch;
while ((ch = getchar()) != '\n')//获得字符
{
if (isalpha(ch))//判读是否是英文字符
{
if (islower(ch))//判断是小写
{
letlow[ch - 'a'] += 1;
}
else{
letup[ch - 'A'] += 1;
}
}
}
//循环打印
for (int i = 0; i < LETSIZE; ++i)
{
printf("%c=>%d\n", i + 'a', letlow[i]);
}
for (int i = 0; i < LETSIZE; ++i)
{
printf("%c=>%d\n", i + 'A', letup[i]);
}
return 0;
}
今天也要好好学习呀~