C语言,统计二维字符数组中字母,数字,空格,其他字符的个数,用循环,输入每行的字符串
时间: 2024-01-07 14:03:22 浏览: 118
C语言程序设计-输入一行字符,分别统计出英文大小写字母、空格、数字和其他字符的个数
5星 · 资源好评率100%
可以使用两层循环,第一层循环遍历输入的每一行字符串,第二层循环遍历当前行字符串的每一个字符,然后使用if-else语句进行分类统计。
具体代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char arr[100][100];
int n, letter_count, digit_count, space_count, other_count;
printf("Enter the number of lines: ");
scanf("%d", &n);
getchar(); // 吃掉输入数字后的回车符
for (int i = 0; i < n; i++) {
printf("Enter string %d: ", i+1);
gets(arr[i]); // 获取当前行字符串
}
for (int i = 0; i < n; i++) {
letter_count = digit_count = space_count = other_count = 0; // 每次循环前先清零
for (int j = 0; j < strlen(arr[i]); j++) {
if (arr[i][j] >= 'a' && arr[i][j] <= 'z' || arr[i][j] >= 'A' && arr[i][j] <= 'Z') {
letter_count++;
} else if (arr[i][j] >= '0' && arr[i][j] <= '9') {
digit_count++;
} else if (arr[i][j] == ' ') {
space_count++;
} else {
other_count++;
}
}
printf("Line %d:\n", i+1);
printf("Letter count: %d\n", letter_count);
printf("Digit count: %d\n", digit_count);
printf("Space count: %d\n", space_count);
printf("Other count: %d\n", other_count);
}
return 0;
}
```
示例输入:
```
Enter the number of lines: 3
Enter string 1: Hello World!
Enter string 2: 12345 abcdefg
Enter string 3: ^&$#)
```
输出结果:
```
Line 1:
Letter count: 10
Digit count: 0
Space count: 1
Other count: 1
Line 2:
Letter count: 7
Digit count: 5
Space count: 1
Other count: 0
Line 3:
Letter count: 0
Digit count: 0
Space count: 0
Other count: 6
```
阅读全文