找出该字符串中重复的字符
时间: 2023-10-15 10:05:30 浏览: 37
假设该字符串为 str,可以使用字典来统计每个字符出现的次数,最后输出出现次数大于 1 的字符即可。
以下是 Python 代码实现:
```
str = "hello world"
char_count = {}
for char in str:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in char_count:
if char_count[char] > 1:
print(char)
```
输出结果为:
```
l
o
```
相关问题
找出该字符串中重复的字符用declare做
以下是使用declare声明变量并找出字符串中重复字符的示例代码:
```bash
#!/bin/bash
str="hello world"
declare -A char_count
# 统计每个字符出现的次数
for ((i=0; i<${#str}; i++)); do
char=${str:$i:1}
if [[ ${char_count[$char]+_} ]]; then
char_count[$char]=$((char_count[$char]+1))
else
char_count[$char]=1
fi
done
# 输出重复的字符
for char in "${!char_count[@]}"; do
if (( char_count[$char] > 1 )); then
echo "$char appears ${char_count[$char]} times"
fi
done
```
解释:
- 第2行定义了要检查的字符串。
- 第3行使用`declare -A`命令声明了一个关联数组`char_count`,用于统计每个字符出现的次数。
- 第6~11行使用循环遍历字符串中的每个字符,并将其出现次数存储在`char_count`数组中。
- 第14~18行使用另一个循环遍历`char_count`数组,输出出现次数大于1的字符。
注意,这个脚本只是一个示例,可能并不适用于所有情况。在实际使用中,需要根据具体的需求进行修改。
找出该字符串中重复的字符用创建函数做
以下是使用函数实现查找字符串中重复字符的示例代码:
```python
def find_duplicates(string):
"""
在给定的字符串中查找重复字符
:param string: 要查找的字符串
:return: 重复字符列表
"""
duplicates = []
for char in string:
if string.count(char) > 1 and char not in duplicates:
duplicates.append(char)
return duplicates
# 测试
print(find_duplicates("hello world"))
```
输出结果为 `['l', 'o']`,表示在字符串 "hello world" 中,字符 'l' 和 'o' 是重复的。