编写一个程序,输入一个字符串,统计其中的字母、数字和其他字符的个数。
#include
#include
int main()
char str[100];
int alphabets = 0, digits = 0, others = 0;
printf("输入字符串:");
gets(str);
for (int i = 0; str[i] != '\0'; i++)
if (isalpha(str[i])) alphabets++;
else if (isdigit(str[i])) digits++;
else others++;
printf("字母个数:%d\n", alphabets);
printf("数字个数:%d\n", digits);
printf("其他字符个数:%d\n", others);
return 0;
当我们输入一个字符串后,程序会逐个遍历每个字符。对于每个字符,程序会使用isalpha()判断它是否为字母,使用isdigit()判断它是否为数字,如果都不是,则说明它是其他字符。
如果是字母字符,则将字母计数器alphabets加 1;如果是数字字符,则将数字计数器digits加 1;如果是其他字符,则将其他字符计数器others加 1。
最后,程序输出三个计数器的值,即为该字符串中字母、数字和其他字符的个数。
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.