输入一行字符,长度不超过100,请你统计一下其中的数字字符的个数。
时间: 2023-05-28 10:04:42 浏览: 71
算法1:遍历字符串,判断每个字符是否为数字字符,若是则计数器加1
时间复杂度:$O(n)$
空间复杂度:$O(1)$
C++ 代码
```cpp
#include <iostream>
using namespace std;
int main() {
string s;
getline(cin, s); // 输入一行字符串
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] >= '0' && s[i] <= '9') cnt++; // 判断是否为数字字符
}
cout << cnt << endl; // 输出个数
return 0;
}
```
算法2:使用isdigit()函数判断字符是否为数字字符
时间复杂度:$O(n)$
空间复杂度:$O(1)$
C++ 代码
```cpp
#include <iostream>
using namespace std;
int main() {
string s;
getline(cin, s); // 输入一行字符串
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
if (isdigit(s[i])) cnt++; // 判断是否为数字字符
}
cout << cnt << endl; // 输出个数
return 0;
}
```
相关问题
编写程序,能够输入一行字符(长度不确定),统计其中的大写字母、小写字母和数字的个数C++
下面是一个简单的 C++ 程序,可以实现你所描述的功能:
```cpp
#include <iostream>
using namespace std;
int main()
{
char str[100];
int upper = 0, lower = 0, digit = 0;
cout << "请输入一行字符:";
cin.getline(str, 100);
for (int i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
upper++;
} else if (islower(str[i])) {
lower++;
} else if (isdigit(str[i])) {
digit++;
}
}
cout << "大写字母个数:" << upper << endl;
cout << "小写字母个数:" << lower << endl;
cout << "数字个数:" << digit << endl;
return 0;
}
```
程序中使用了 `isupper()`、`islower()` 和 `isdigit()` 函数来判断字符的类型。其中,`isupper()` 函数用于判断一个字符是否为大写字母,返回值为非零表示是大写字母,否则为小写字母或其他字符;`islower()` 函数用于判断一个字符是否为小写字母,返回值为非零表示是小写字母,否则为大写字母或其他字符;`isdigit()` 函数用于判断一个字符是否为数字字符,返回值为非零表示是数字字符,否则为其他字符。
编写程序,能够输入一行字符(长度不确定),统计其中的大写字母、小写字母和数字的个数。
以下是 Python 代码实现:
```
string = input("请输入一行字符:")
upper_count = 0
lower_count = 0
digit_count = 0
for char in string:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
elif char.isdigit():
digit_count += 1
print("大写字母个数:", upper_count)
print("小写字母个数:", lower_count)
print("数字个数:", digit_count)
```
代码中使用 `input()` 函数获取用户输入,然后使用 `for` 循环遍历输入字符串的每个字符,对于每个字符,使用 `isupper()` 判断是否为大写字母,使用 `islower()` 判断是否为小写字母,使用 `isdigit()` 判断是否为数字。根据判断结果,累加计数器。最后输出大写字母个数、小写字母个数和数字个数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)