写一串代码统计每个 字符出现的次数c++
时间: 2023-06-03 20:04:24 浏览: 100
当然,没问题!以下是示例代码:
```
#include <iostream>
#include <map>
using namespace std;
int main() {
string str;
cout << "请输入一个字符串: ";
getline(cin, str);
map<char, int> count_map;
for (char ch : str) {
if (isalnum(ch)) {
count_map[ch]++;
}
}
for (auto it = count_map.begin(); it != count_map.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
```
这段代码可以统计输入字符串中所有字母和数字出现的次数,忽略其他字符。
相关问题
c++统计字符串中每个字符出现的次数
可以使用一个数组来记录每个字符出现的次数,数组的下标表示字符的ASCII码值,数组的值表示该字符出现的次数。具体实现如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[100];
int count[256] = {0}; // 初始化数组为0
cout << "请输入一个字符串:";
cin >> str;
int len = strlen(str);
for (int i = 0; i < len; i++)
{
count[str[i]]++; // 统计字符出现次数
}
for (int i = 0; i < 256; i++)
{
if (count[i] != 0)
{
cout << "字符 " << (char)i << " 出现了 " << count[i] << " 次" << endl;
}
}
return 0;
}
```
运行结果:
```
请输入一个字符串:hello world
字符 出现了 1 次
字符 d 出现了 1 次
字符 e 出现了 1 次
字符 h 出现了 1 次
字符 l 出现了 3 次
字符 o 出现了 2 次
字符 r 出现了 1 次
字符 w 出现了 1 次
```
c++ 输入一个字符串,统计所有字符出现的次数
可以使用数组来记录每个字符出现的次数,具体实现如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count[256] = {0}; // 用数组记录每个字符出现的次数,数组大小为 256,因为 ASCII 码共有 256 个字符
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
for (int i = 0; i < len; i++) {
count[str[i]]++; // 对应字符出现的次数加 1
}
printf("每个字符出现的次数如下:\n");
for (int i = 0; i < 256; i++) {
if (count[i] != 0) {
printf("%c:%d\n", i, count[i]);
}
}
return 0;
}
```
这里使用了一个大小为 256 的数组 `count` 来记录每个字符出现的次数,其中下标表示对应的 ASCII 码,因此遍历字符串时只需要对 `count[str[i]]` 进行加 1 操作即可。最后遍历数组输出每个字符出现的次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)