输入一个字符串,分别统计其中数字、空格、字母及其他字符(除数字、字母、空格之外的)出现的次数。 例如: 输入:China 1949.10.1~2010.10.1 C语言
时间: 2023-07-10 14:23:10 浏览: 88
好的,以下是 Python 和 C 语言的代码实现:
Python 代码实现:
```python
def count_chars(s):
num_count = 0
space_count = 0
letter_count = 0
other_count = 0
for ch in s:
if ch.isdigit():
num_count += 1
elif ch.isspace():
space_count += 1
elif ch.isalpha():
letter_count += 1
else:
other_count += 1
print("数字个数:", num_count)
print("空格个数:", space_count)
print("字母个数:", letter_count)
print("其他字符个数:", other_count)
# 测试代码
s = "China 1949.10.1~2010.10.1 C语言"
count_chars(s)
```
在上面的代码中,我们定义了一个 `count_chars` 函数,该函数接受一个字符串参数 `s`,并统计其中数字、空格、字母及其他字符(除数字、字母、空格之外的)出现的次数。使用 `isdigit` 函数判断字符是否为数字,使用 `isspace` 函数判断字符是否为空格,使用 `isalpha` 函数判断字符是否为字母。
C 语言代码实现:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *s) {
int num_count = 0;
int space_count = 0;
int letter_count = 0;
int other_count = 0;
while (*s != '\0') {
if (isdigit(*s)) {
num_count++;
} else if (isspace(*s)) {
space_count++;
} else if (isalpha(*s)) {
letter_count++;
} else {
other_count++;
}
s++;
}
printf("数字个数:%d\n", num_count);
printf("空格个数:%d\n", space_count);
printf("字母个数:%d\n", letter_count);
printf("其他字符个数:%d\n", other_count);
}
// 测试代码
int main() {
char s[] = "China 1949.10.1~2010.10.1 C语言";
count_chars(s);
return 0;
}
```
在上面的代码中,我们定义了一个 `count_chars` 函数,该函数接受一个字符指针 `s`,并统计其中数字、空格、字母及其他字符(除数字、字母、空格之外的)出现的次数。使用 `isdigit` 函数判断字符是否为数字,使用 `isspace` 函数判断字符是否为空格,使用 `isalpha` 函数判断字符是否为字母。
在测试代码中,我们将 `s` 设置为 "China 1949.10.1~2010.10.1 C语言",测试了程序的正确性。