输入一个字符和一个字符串(少于50个字符),在字符串中查找该字符。若找到,则输出该字符在字符串中所对应的最大下标,下标从0开始;否则输出“Not Found”。
时间: 2024-03-25 10:39:09 浏览: 9
好的,这是一个简单的字符串查找问题,我可以帮您写出以下 Python 代码示例:
```
char = input("请输入要查找的字符:")
string = input("请输入字符串:")
if len(string) >= 50:
print("字符串长度不能超过50个字符!")
else:
index = -1 # 初始化下标为-1,表示未找到
for i in range(len(string)):
if string[i] == char:
index = i
if index == -1:
print("Not Found")
else:
print("该字符在字符串中所对应的最大下标为:", index)
```
您可以将以上代码复制到 Python 环境中运行,输入字符和字符串,即可得到结果。
相关问题
输入一个字符串数组和一个字符查找并输出字符在字符串数组中首次出现的位置
好的,可以使用以下 Python 代码实现:
```python
def find_char(strs, char):
for i in range(len(strs)):
if char in strs[i]:
return i, strs[i].index(char)
return -1, -1
strs = ['hello', 'world', 'python', 'code']
char = 'o'
index, pos = find_char(strs, char)
if index == -1:
print(f"字符 '{char}' 未在字符串数组中出现")
else:
print(f"字符 '{char}' 在字符串数组中首次出现的位置为第 {index+1} 个字符串的第 {pos+1} 个字符")
```
这里定义了一个名为 `find_char` 的函数,接受两个参数:一个字符串数组 `strs` 和一个字符 `char`。函数首先遍历字符串数组中的每个字符串,判断字符是否在该字符串中出现。如果找到了,就返回该字符串在字符串数组中的索引和字符在该字符串中的位置。如果遍历完整个字符串数组都没有找到该字符,就返回 `-1, -1` 表示未找到。
接下来,我们定义一个字符串数组 `strs` 和一个字符 `char`。然后调用 `find_char` 函数,获取字符在字符串数组中的位置。如果位置为 `-1`,说明字符未出现在字符串数组中;否则就输出字符在字符串数组中首次出现的位置。
接受用户输入一个字符串和一个字符,然后输出该字符串中包含
该字符的所有位置。
示例输入:
字符串:hello world
字符:o
示例输出:
o出现在第5个位置
o出现在第8个位置
o出现在第10个位置
代码实现:
```
string = input("请输入一个字符串:")
char = input("请输入一个字符:")
for i in range(len(string)):
if string[i] == char:
print(char + "出现在第" + str(i+1) + "个位置")
```
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.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)