任意输入一串字符串,输出其中的不同字符及其个数。例如:输入abcdefgabc,输出为a->2,b->2,c->2,d->1,e->1,f->1,g->1。
时间: 2024-05-05 10:20:54 浏览: 87
您可以使用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 char, count in char_dict.items():
print(char, "->", count)
```
运行示例:
```
请输入字符串:abcdefgabc
a -> 2
b -> 2
c -> 2
d -> 1
e -> 1
f -> 1
g -> 1
```
相关问题
任意输入一串字符串,输出其中的不同字符及其个数。例如:输入abcdefgabc,输出为a->2,b->2,c->2,d->1,e->1,f->1,g->1。
您可以参考以下 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 char, count in char_dict.items():
print(f'{char}->{count}', end=',')
```
代码实现的思路是创建一个空字典 `char_dict`,遍历输入的字符串 `string` 中的每一个字符,如果该字符已经在字典中,则将计数器加 1,否则将该字符添加到字典中,并将计数器初始化为 1。最后遍历字典中的键值对,输出每个不同字符和其对应的计数。
c++任意输入一串字符串,输出其中的不同字符及其个数。例如:输入abcdefgabc,输出为a->2,b->2,c->2,d->1,e->1,f->1,g->1。
可以使用哈希表来记录每个字符出现的次数,然后遍历哈希表输出结果。
以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
int main() {
char str[MAX_LEN];
int count[128] = {0}; // 哈希表
printf("请输入一个字符串:");
fgets(str, MAX_LEN, stdin);
str[strcspn(str, "\n")] = '\0'; // 去掉字符串末尾的换行符
// 统计每个字符出现的次数
for (int i = 0; i < strlen(str); i++) {
count[(int)str[i]]++;
}
// 输出结果
for (int i = 0; i < 128; i++) {
if (count[i] > 0) {
printf("%c->%d,", i, count[i]);
}
}
printf("\n");
return 0;
}
```
输入示例:
```
请输入一个字符串:abcdefgabc
```
输出示例:
```
a->2,b->2,c->2,d->1,e->1,f->1,g->1,
```
阅读全文
相关推荐













