输入一行字符分别统计出其中英文字母、数字、空格和其他字符的个数。输入一行字符输出统计值样例输入 aklsjflj123 sadf918u324 asdf91u32oasdf;123样例输出23 16 2 4用c语言写
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
gets(str);
int letter_count = 0;
int digit_count = 0;
int space_count = 0;
int other_count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letter_count++;
} else if (isdigit(str[i])) {
digit_count++;
} else if (isspace(str[i])) {
space_count++;
} else {
other_count++;
}
}
printf("%d %d %d %d\n", letter_count, digit_count, space_count, other_count);
return 0;
}
注意:使用 gets 函数时需要包含头文件 #include <stdio.h>,并且该函数在 C11 标准中已被弃用。建议使用 fgets 函数代替。使用 fgets 函数时,需要将换行符也读取到字符串中,因此需要将换行符从统计的空格字符数中减去。示例代码如下:
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
fgets(str, sizeof(str), stdin);
int letter_count = 0;
int digit_count = 0;
int space_count = 0;
int other_count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letter_count++;
} else if (isdigit(str[i])) {
digit_count++;
} else if (isspace(str[i])) {
space_count++;
} else {
other_count++;
}
}
printf("%d %d %d %d\n", letter_count, digit_count, space_count - 1, other_count);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/hBCA 著作权归作者所有。请勿转载和采集!