2、编写程序实现在一个字符串中查找指定的字符,并输出指定的字符在字符串中出现的次数及位置,如果该字符串中不包含指定的字符,请输出提示信
时间: 2024-05-14 21:15:19 浏览: 166
好的,以下是 Python 代码实现:
```python
str_input = input("请输入一个字符串:")
char_input = input("请输入要查找的字符:")
# 初始化计数器和位置列表
count = 0
pos_list = []
# 遍历字符串,查找指定字符
for index, char in enumerate(str_input):
if char == char_input:
count += 1
pos_list.append(index)
# 输出结果
if count == 0:
print("该字符串中不包含指定的字符。")
else:
print(f"指定的字符在字符串中出现了 {count} 次,位置分别为:{pos_list}")
```
运行程序后,输入字符串和要查找的字符,即可输出结果。例如,输入字符串为 "hello world",要查找的字符为 "l",则程序输出:
```
指定的字符在字符串中出现了 3 次,位置分别为:[2, 3, 9]
```
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![cc](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)