c++统计字符串数字字符出现的次数
时间: 2023-12-09 19:06:10 浏览: 256
以下是C++统计字符串数字字符出现次数的代码示例:
```c++
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
string s;
cin >> s;
map<char, int> m;
for (auto & i : s) {
if (isdigit(i)) { // 判断是否为数字字符
m[i]++;
}
}
for (auto & i : m) {
cout << i.first << ' ' << i.second << endl;
}
return 0;
}
```
该代码使用了STL中的map容器,遍历字符串中的每个字符,判断是否为数字字符,如果是,则将该字符作为键值存入map中,并将对应的值加1。最后遍历map,输出每个数字字符及其出现次数。
相关问题
c++统计字符串中数字出现个数
在 C++ 中,你可以使用标准库函数和遍历算法来统计字符串中数字的出现次数。这里是一个简单的示例,它会遍历整个字符串并检查每个字符是否为数字:
```cpp
#include <iostream>
#include <string>
#include <cctype> // 包含 isdigit 函数
int count_digits(const std::string& str) {
int count = 0;
for (char c : str) {
if (std::isdigit(c)) { // 使用 isdigit 判断字符是否为数字
count++;
}
}
return count;
}
int main() {
std::string input = "abc123def456";
int digit_count = count_digits(input);
std::cout << "The number of digits in the string is: " << digit_count << std::endl;
return 0;
}
```
这个`count_digits`函数会返回给定字符串中数字的数量。
c++输入字符串编程统计出I4中共出现了多少个数字字符进一步考虑如何统计出10个数字字符各出现的次数
在C++中,你可以通过遍历输入的字符串,并利用条件判断来统计其中的数字字符以及各个数字字符的具体出现次数。这里是一个简单的示例:
```cpp
#include <iostream>
#include <string>
int count_digits(const std::string &input) {
int digit_counts[10] = {0}; // 初始化一个数组存放每个数字0-9的计数
for (char c : input) {
if (isdigit(c)) { // 判断字符是否为数字
int digit = c - '0'; // 将字符转换成对应的整数值(ASCII码减去'0')
digit_counts[digit]++;
}
}
return digit_counts; // 返回包含每个数字字符计数的数组
}
std::string get_digit_counts(int counts[]) {
std::string result = "";
for (int i = 0; i < 10; i++) {
if (counts[i]) {
result += "数字" + std::to_string(i) + ": " + std::to_string(counts[i]) + " 次, ";
}
}
if (!result.empty()) {
result.pop_back(); // 移除最后一个逗号和空格
}
return result;
}
int main() {
std::string input_str;
std::cout << "请输入字符串: ";
std::getline(std::cin, input_str);
int counts[] = count_digits(input_str);
std::string digit_stats = get_digit_counts(counts);
std::cout << "每个数字字符的出现次数:\n" << digit_stats << std::endl;
return 0;
}
```
在这个程序中,`count_digits` 函数遍历字符串并统计每个数字字符的出现次数,存储在 `digit_counts` 数组中。`get_digit_counts` 函数将数组的内容整理成易于理解的形式。
运行这个程序时,它会提示用户输入字符串,然后显示每个数字字符及其出现次数。
阅读全文
相关推荐
















