请以“任意输入一串字符串,输出其中的不同字符及其个数。例如:输入abcdefgabc,输出为a->2,b->2,c->2,d->1,e->1,f->1,g->1。”为目的写一个C++程序
时间: 2024-05-01 18:21:44 浏览: 13
好的,以下是一个简单的实现:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char input[100];
int count[128] = {0}; // 用一个数组记录每个字符出现的次数,ASCII码最大为127
printf("请输入一个字符串:");
scanf("%s", input);
int len = strlen(input);
for (int i = 0; i < len; i++)
{
count[(int)input[i]]++; // 字符出现次数加1
}
printf("不同字符及其个数为:\n");
for (int i = 0; i < 128; i++)
{
if (count[i] > 0)
{
printf("%c->%d,", (char)i, count[i]); // 输出结果
}
}
return 0;
}
```
注意,此程序假设输入的字符串只包含 ASCII 码字符,如果输入的字符串中包含其他字符,程序可能会出错。
相关问题
C++任意输入一串字符串,输出其中的不同字符及其个数。例如:输入abcdefgabc,输出为a->2,b->2,c->2,d->1,e->1,f->1,g->1。
可以使用一个数组记录每个字符出现的次数,然后遍历数组输出不同字符及其个数。
以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int count[256] = {0}; // 用一个大小为 256 的数组记录每个字符出现的次数
printf("请输入一串字符串:");
scanf("%s", str);
// 遍历字符串,记录每个字符出现的次数
for (int i = 0; i < strlen(str); i++) {
count[str[i]]++;
}
// 输出不同字符及其个数
for (int i = 0; i < 256; i++) {
if (count[i] > 0) {
printf("%c->%d,", i, count[i]);
}
}
return 0;
}
```
输出结果如下:
```
请输入一串字符串:abcdefgabc
a->2,b->2,c->2,d->1,e->1,f->1,g->1,
```
python任意输入一串字符串,输出其中的不同字符及其个数。例如:输入abcdefgabc,输出为a->2,b->2,c->2,d->1,e->1,f->1,g->1。
可以使用 Python 中的字典来实现这个功能。遍历字符串中的每个字符,如果该字符还没有在字典中出现过,则将其添加到字典中,对应的值为 1;如果该字符已经在字典中出现过,则将对应的值加 1。最后输出字典中的键值对即可。
代码如下:
```python
s = input("请输入一个字符串:")
# 定义一个空字典,用于存储字符及其出现次数
count = {}
# 遍历字符串中的每个字符
for c in s:
# 如果该字符还没有在字典中出现过,则将其添加到字典中,对应的值为 1
if c not in count:
count[c] = 1
# 如果该字符已经在字典中出现过,则将对应的值加 1
else:
count[c] += 1
# 输出字典中的键值对
for k, v in count.items():
print(f"{k}->{v}")
```
运行结果如下:
```
请输入一个字符串:abcdefgabc
a->2
b->2
c->2
d->1
e->1
f->1
g->1
```
相关推荐
![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)