题目::输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数?
程序分析
我们需要编写一个程序,统计输入的一行字符中的英文字母、空格、数字和其他字符的个数。首先,我们可以使用字符输入函数(例如getchar()
)逐个读取字符,然后根据字符的属性进行统计。
解题思路
- 使用
getchar()
函数逐个读取输入的字符。 - 对每个字符进行判断,判断其是否为英文字母、空格、数字或其他字符。
- 根据判断结果对相应的计数器进行增加。
- 输出统计结果。
方法1: 使用单个变量和判断语句
#include <stdio.h>
int main() {
char c;
int letter_count = 0, space_count = 0, digit_count = 0, other_count = 0;
printf("Enter a line of characters: ");
while ((c = getchar()) != '\n') {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
letter_count++;
} else if (c == ' ') {
space_count++;
} else if (c >= '0' && c <= '9') {
digit_count++;
} else {
other_count++;
}
}
printf("Letters: %d\n", letter_count);
printf("Spaces: %d\n", space_count);
printf("Digits: %d\n", digit_count);
printf("Others: %d\n", other_count);
return 0;
}
优缺点:
- 优点:
- 简单直观,易于理解和实现。
- 缺点:
- 逻辑较为繁琐,需要多次使用条件判断。
方法2: 使用数组进行统计
#include <stdio.h>
int main() {
char c;
int counts[4] = {0}; // 0: letters, 1: spaces, 2: digits, 3: others
printf("Enter a line of characters: ");
while ((c = getchar()) != '\n') {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
counts[0]++;
} else if (c == ' ') {
counts[1]++;
} else if (c >= '0' && c <= '9') {
counts[2]++;
} else {
counts[3]++;
}
}
printf("Letters: %d\n", counts[0]);
printf("Spaces: %d\n", counts[1]);
printf("Digits: %d\n", counts[2]);
printf("Others: %d\n", counts[3]);
return 0;
}
优缺点:
- 优点:
- 使用数组简化了统计逻辑,减少了重复代码。
- 缺点:
- 需要额外的数组空间,可能浪费一些内存。
方法3: 使用位运算进行统计
#include <stdio.h>
int main() {
char c;
int counts = 0; // Bits: 0 - letters, 1 - spaces, 2 - digits, 3 - others
printf("Enter a line of characters: ");
while ((c = getchar()) != '\n') {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
counts |= 1; // Set the first bit for letters
} else if (c == ' ') {
counts |= 2; // Set the second bit for spaces
} else if (c >= '0' && c <= '9') {
counts |= 4; // Set the third bit for digits
} else {
counts |= 8; // Set the fourth bit for others
}
}
printf("Letters: %d\n", (counts & 1) ? 1 : 0);
printf("Spaces: %d\n", (counts & 2) ? 1 : 0);
printf("Digits: %d\n", (counts & 4) ? 1 : 0);
printf("Others: %d\n", (counts & 8) ? 1 : 0);
return 0;
}
优缺点:
- 优点:
- 使用位运算减少了空间复杂度,不需要额外的 array。
- 简化了统计逻辑,减少了重复代码。
- 缺点:
- 可能不容易理解位运算的初学者。
总结
推荐方法2(使用数组进行统计)作为最好的实现方式,因为它综合了简洁性、可读性和扩展性。它避免了方法1中繁琐的多次条件判断,同时不引入复杂的位运算。数组的索引清晰地表示了各种字符类型的计数,易于理解和维护。虽然它可能会占用一些额外的内存空间,但这种额外的空间消耗通常可以忽略不计,并且带来了更清晰的代码结构。