编写一个函数,从键盘输入一个字符串,统计其中字母、数字、空格和其他字符的个数。在主函数中进行调用,并实现测试。
时间: 2023-11-17 21:05:41 浏览: 105
```python
def count_chars():
s = input("请输入一个字符串:")
letters = 0
digits = 0
spaces = 0
others = 0
for c in s:
if c.isalpha():
letters += 1
elif c.isdigit():
digits += 1
elif c.isspace():
spaces += 1
else:
others += 1
print("字母个数:", letters)
print("数字个数:", digits)
print("空格个数:", spaces)
print("其他字符个数:", others)
count_chars()
```
测试:
```
请输入一个字符串:Hello World! 123
字母个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 1
```
相关问题
用C语言编写一个函数,从键盘输入一个字符串,统计其中字母、数字、空格和其他字符的个数。在主函数中进行调用,并实现测试。
```
#include <stdio.h>
#include <ctype.h>
void count(char *str){
int letter = 0, digit = 0, space = 0, other = 0;
while(*str){
if(isalpha(*str)){
letter++;
}else if(isdigit(*str)){
digit++;
}else if(isspace(*str)){
space++;
}else{
other++;
}
str++;
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
}
int main(){
char str[100];
printf("请输入一个字符串:");
fgets(str, 100, stdin);
count(str);
return 0;
}
```
c语言编写一个函数,统计一个输入字符串中字母、数字、空格和其他字符的个数
可以使用C语言中的字符函数库ctype.h中的函数来判断字符的类型。具体实现如下:
```c
#include <stdio.h>
#include <ctype.h>
void countChars(char *str, int *letters, int *digits, int *spaces, int *others) {
while (*str) {
if (isalpha(*str)) { // 判断字母
(*letters)++;
} else if (isdigit(*str)) { // 判断数字
(*digits)++;
} else if (isspace(*str)) { // 判断空格
(*spaces)++;
} else { // 其他字符
(*others)++;
}
str++; // 指针后移
}
}
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入字符串:");
gets(str); // 读入字符串
countChars(str, &letters, &digits, &spaces, &others);
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
注意,上述代码使用了gets函数读入字符串,但是gets函数有安全性问题,可以使用fgets函数替代。同时,由于C语言中没有字符串类型,所以我们使用字符数组来表示字符串。