用C++实现输入一行字符,分别统计出其数字、大写字母、小写字母和其他字符
时间: 2023-05-12 11:03:30 浏览: 61
好的,这个问题可以回答。以下是用C语言实现输入一行字符,分别统计出其数字、大写字母、小写字母和其他字符的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int digits = 0, uppercase = 0, lowercase = 0, other = 0;
printf("请输入一行字符:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
digits++;
} else if (isupper(str[i])) {
uppercase++;
} else if (islower(str[i])) {
lowercase++;
} else {
other++;
}
}
printf("数字:%d\n大写字母:%d\n小写字母:%d\n其他字符:%d\n", digits, uppercase, lowercase, other);
return 0;
}
```
希望这个代码对你有帮助!
相关问题
c++输入一行字符串,计算出字符串的长度,并分别统计大写字母、小写字母、数字和其
题目要求编写一个程序,输入一行字符串后,统计该字符串的长度,并分别统计出其中包含多少个大写字母、小写字母、数字和其他字符。以下是一个简单的Python程序实现:
```python
string = input("请输入一个字符串:") # 输入字符串
length = len(string) # 计算字符串长度
upper_count = 0 # 大写字母计数器
lower_count = 0 # 小写字母计数器
digit_count = 0 # 数字计数器
other_count = 0 # 其他字符计数器
for char in string:
if char.isupper():
upper_count += 1 # 大写字母累加
elif char.islower():
lower_count += 1 # 小写字母累加
elif char.isdigit():
digit_count += 1 # 数字累加
else:
other_count += 1 # 其他字符累加
print("输入的字符串长度为:", length)
print("其中包含大写字母", upper_count, "个")
print("其中包含小写字母", lower_count, "个")
print("其中包含数字", digit_count, "个")
print("其中包含其他字符", other_count, "个")
```
程序的实现比较简单,首先从用户处输入一个字符串,然后通过 `len()` 函数获取字符串的长度。接着定义四个计数器,用于统计大写字母、小写字母、数字和其他字符的数量。程序通过一个 for 循环遍历字符串的每一个字符,如果该字符是大写字母则累加到 `upper_count` 中,如果是小写字母则累加到 `lower_count` 中,如果是数字则累加到 `digit_count` 中,如果是其他字符则累加到 `other_count` 中。最后,程序输出长度、大写字母数、小写字母数、数字数和其他字符数。
用c++实现输入一段字符,要求分别统计出其中英文大写字母,小写字母,数字,空格,以及其他字符的个数
好的,以下是 C++ 代码实现:
```c++
#include <iostream>
#include <cctype> // 用于判断字符类型
using namespace std;
int main() {
string s;
int upper = 0, lower = 0, digit = 0, space = 0, other = 0;
cout << "请输入一段字符:" << endl;
getline(cin, s); // 读入一行字符串
for (char c : s) {
if (isupper(c)) // 判断大写字母
upper++;
else if (islower(c)) // 判断小写字母
lower++;
else if (isdigit(c)) // 判断数字
digit++;
else if (isspace(c)) // 判断空格
space++;
else // 其他字符
other++;
}
cout << "大写字母个数:" << upper << endl;
cout << "小写字母个数:" << lower << endl;
cout << "数字个数:" << digit << endl;
cout << "空格个数:" << space << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
运行程序后,输入一段字符,即可得到分别统计出其中英文大写字母,小写字母,数字,空格,以及其他字符的个数。