统计字符出现的次数c++
时间: 2024-06-13 16:10:08 浏览: 13
以下是使用C++统计字符出现次数的示例代码:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
string str = "hello world";
unordered_map<char, int> count_map;
for (char c : str) {
count_map[c]++;
}
for (auto it : count_map) {
cout << it.first << ": " << it.second << endl;
}
return 0;
}
```
上述代码中,我们使用了`unordered_map`来存储每个字符出现的次数。首先,我们遍历字符串中的每个字符,将其作为键值存储在`count_map`中,并将其对应的值加1。最后,我们遍历`count_map`,输出每个字符及其出现的次数。
相关问题
统计字符出现次数C++
以下是C++中统计字符出现次数的例子:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
string s = "aabbbcddddeeffffghijklmnopqrst";
unordered_map<char, int> mp;
for (char c : s) {
mp[c]++;
}
char max_char = ' ';
int max_count = 0;
for (auto p : mp) {
if (p.second > max_count) {
max_count = p.second;
max_char = p.first;
}
}
cout << "出现最多的字符是:" << max_char << endl;
cout << "出现次数为:" << max_count << endl;
return 0;
}
```
统计字符串出现的次数c++
你需要输入一个字符串和一个目标字符,然后统计目标字符在字符串中出现的次数c,下面是一个Python实现的例子:
```python
def count_occurrences(string, target):
c = 0
for char in string:
if char == target:
c += 1
return c
string = "Hello, world!"
target = "l"
print(count_occurrences(string, target)) # 输出2
```
在上面的例子中,我们定义了一个名为`count_occurrences`的函数,它接受两个参数:一个字符串和一个目标字符。然后我们定义了一个变量`c`,用于保存目标字符在字符串中出现的次数。我们遍历字符串中的每个字符,如果当前字符等于目标字符,则将`c`加1。最后返回`c`的值。
在代码中,我们使用了字符串`"Hello, world!"`和目标字符`"l"`来测试函数。函数输出2,说明在字符串中字符`"l"`出现了2次。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)