c 语言 编写程序,输入一个字符串,分别统计并输出其中的数字字符、空格字符和其他字符出现的次数。
时间: 2024-02-06 18:10:00 浏览: 26
可以使用 ASCII 码表进行字符类型的判断,以下是一个简单的示例程序:
```c
#include <stdio.h>
int main() {
char str[100];
int digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:");
gets(str); // 此函数不安全,建议使用 fgets
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= '0' && str[i] <= '9') {
digits++;
} else if (str[i] == ' ') {
spaces++;
} else {
others++;
}
}
printf("数字字符出现了 %d 次\n", digits);
printf("空格字符出现了 %d 次\n", spaces);
printf("其他字符出现了 %d 次\n", others);
return 0;
}
```
运行程序后,输入一个字符串,即可输出其中数字字符、空格字符和其他字符出现的次数。请注意,此程序使用了不安全的 `gets` 函数,实际应用中应该使用更安全的 `fgets` 函数来读取输入的字符串。
相关问题
.编写一个C语言程序,输入一个字符串,统计其中的字母、数字、空格和其他字符的个数并输出
好的,以下是您需要的C语言程序:
```c
#include<stdio.h>
int main(){
char str[100];
int i, alphabet, digit, space, other;
alphabet = digit = space = other = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for(i=0; str[i]!='\0'; i++){
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
alphabet++;
else if(str[i]>='0' && str[i]<='9')
digit++;
else if(str[i]==' ')
space++;
else
other++;
}
printf("字母个数:%d\n", alphabet);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```
程序说明:
1. 首先定义了一个字符数组 `str`,用于存储输入的字符串。
2. 定义了四个整型变量 `alphabet`、`digit`、`space` 和 `other`,用于统计字母、数字、空格和其他字符的个数。
3. 调用 `fgets()` 函数从标准输入流中读取字符串,并将其存储到 `str` 数组中。
4. 使用 `for` 循环遍历字符串中的每一个字符,判断其类型,并对相应的计数器进行加一操作。
5. 最后输出各种字符的个数。
注意:由于输入的字符串可能包含空格,因此不能使用 `scanf()` 函数直接读取字符串,需要使用 `fgets()` 函数读取。
编写程序,从键盘输入一行字符串,统计并输出其中英文、数字、空格和其他字符的个数。
```python
string = input("请输入一行字符串:")
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)
```
示例输出:
```
请输入一行字符串:Hello, 123 world!
字母个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 2
```