#include <stdio.h> #include <stdlib.h> int main() {char c; int letters=0,space=0,digit=0,others=0; printf("please input some characters请输入一些字符\n"); while((c=getchar())!='\n') { if(c>='a'&&c<='z'||c>='A'&&c<='Z') letters++; else if(c=='\0') space++; else if(c>='0'&&c<='9') digit++; else others++; } printf("all in all总计:char字符=%d,space空格=%d,digit数字=%d,others其他=%d\n",letters,space,digit,others); } 改编以上程序代码,改编成对输入的字符串内容进行分类并统计数量。
以下是改编后的 C 语言程序代码,用于对输入的字符串内容进行分类并统计数量:
c 复制
#include <stdio.h> #include <stdlib.h> #include <string.h>
int main() { char str[100]; // 定义一个字符串来存储输入 int letters = 0, space = 0, digit = 0, others = 0;
printf("please input a string请输入一个字符串\n");
fgets(str, sizeof(str), stdin); // 使用 fgets 函数获取字符串输入
int len = strlen(str); // 获取字符串长度
for (int i = 0; i < len; i++) // 遍历字符串
{
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
letters++;
else if (str[i] =='\0') // 空格判断
space++;
else if (str[i] >= '0' && str[i] <= '9')
digit++;
else
others++;
}
printf("all in all总计: char字符=%d,space空格=%d,digit数字=%d,others其他=%d\n", letters, space, digit, others);
return 0;
}