任意输入一串字符.输出其中包含的所有各不相同的字符及其个数。例如,输入 abcdefgabc ,输出为 a- >2,b->2,c->2,d->1,e->1,f->1,g->1编写改程序
时间: 2024-05-13 13:19:58 浏览: 16
以下是 Python 代码实现:
```python
string = input("请输入一串字符:")
char_dict = {}
# 遍历字符串,统计各字符出现次数
for char in string:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
# 输出结果
for key, value in char_dict.items():
print(key, "->", value)
```
示例输出:
```
请输入一串字符:abcdefgabc
a -> 2
b -> 2
c -> 2
d -> 1
e -> 1
f -> 1
g -> 1
```
相关问题
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,
```
请用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[128] = {0}; // 用于记录每个字符出现的次数
printf("请输入一串字符串:");
scanf("%s", str);
int len = strlen(str);
for(int i = 0; i < len; i++)
{
count[(int)str[i]]++; // 统计每个字符出现的次数
}
printf("不同字符及其个数如下:\n");
for(int i = 0; i < 128; i++)
{
if(count[i] != 0)
{
printf("%c -> %d\n", i, count[i]); // 输出不同字符及其个数
}
}
return 0;
}
```
程序先让用户输入一串字符串,然后统计每个字符出现的次数,最后输出不同字符及其个数。其中,count数组用于记录每个字符出现的次数,128是ASCII字符集中字符的个数,因此数组的大小为128。
相关推荐
![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)