编写一个函数由实参传来一个字符串统计此字符串中字母数字空格和其他字符的个数在主函数中输入字符串以及输出上述的结果
时间: 2024-04-27 13:13:40 浏览: 223
以下是 Python 代码实现:
```python
def count_chars(string):
letters = 0
digits = 0
spaces = 0
others = 0
for char in string:
if char.isalpha():
letters += 1
elif char.isdigit():
digits += 1
elif char.isspace():
spaces += 1
else:
others += 1
print("字母个数:", letters)
print("数字个数:", digits)
print("空格个数:", spaces)
print("其他字符个数:", others)
# 主函数
if __name__ == '__main__':
string = input("请输入一个字符串: ")
count_chars(string)
```
示例输出:
```
请输入一个字符串: Hello World! 123
字母个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 1
```
相关问题
由C语言实现编写一个函数由实参传来一个字符串统计此字符串中字母数字空格和其他字符的个数在主函数中输入字符串以及输出上述的结果
下面是一个简单的C语言函数,可以统计一个字符串中字母、数字、空格和其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *letters, int *digits, int *spaces, int *others) {
char ch;
*letters = *digits = *spaces = *others = 0;
while ((ch = *str++) != '\0') {
if (isalpha(ch))
(*letters)++;
else if (isdigit(ch))
(*digits)++;
else if (isspace(ch))
(*spaces)++;
else
(*others)++;
}
}
int main() {
char str[100];
int letters, digits, spaces, others;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
count_chars(str, &letters, &digits, &spaces, &others);
printf("Letters: %d\n", letters);
printf("Digits: %d\n", digits);
printf("Spaces: %d\n", spaces);
printf("Other characters: %d\n", others);
return 0;
}
```
在主函数中,我们首先输入一个字符串,然后调用 `count_chars` 函数来统计字符的个数。函数使用 `ctype.h` 中的 `isalpha`、`isdigit` 和 `isspace` 函数来判断字符的类型。在函数中,我们使用指针来返回每种类型字符的个数,因为需要修改这些变量的值。在主函数中,我们只需要打印这些变量的值即可。
统计字符串中字母、数字、空格和其他字符的个数 编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串以及输出上述的结果。
以下是一个C语言程序,它可以统计字符串中字母、数字、空格和其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(const char *str, int *letters, int *digits, int *spaces, int *others) {
*letters = 0;
*digits = 0;
*spaces = 0;
*others = 0;
while (*str) {
if (isalpha(*str)) {
(*letters)++;
} else if (isdigit(*str)) {
(*digits)++;
} else if (isspace(*str)) {
(*spaces)++;
} else {
(*others)++;
}
str++;
}
}
int main() {
char str[1000];
int letters, digits, spaces, others;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
count_chars(str, &letters, &digits, &spaces, &others);
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
这个程序的工作原理如下:
1. 我们定义了一个名为 `count_chars` 的函数,它接受一个字符串和四个整数指针作为参数。
2. 在 `count_chars` 函数中,我们首先将所有计数器初始化为0。
3. 然后,我们使用一个 while 循环遍历字符串的每个字符。
4. 对于每个字符,我们使用 C 标准库中的字符处理函数来判断它的类型:
- `isalpha()` 用于判断字符是否为字母
- `isdigit()` 用于判断字符是否为数字
- `isspace()` 用于判断字符是否为空格
5. 根据字符的类型,我们增加相应的计数器。
6. 在 `main` 函数中,我们从用户那里读取输入的字符串。
7. 然后我们调用 `count_chars` 函数,传入字符串和计数器的地址。
8. 最后,我们打印出每个类别的字符计数。
这个程序可以准确地统计字符串中各种类型字符的个数。它使用了 C 标准库中的字符处理函数,使得代码更加简洁和易读。
阅读全文
相关推荐












