输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有,则输出-1C++
时间: 2024-05-16 11:17:31 浏览: 14
下面是 C++ 的实现代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
char c;
cout << "请输入一个字符串: ";
getline(cin, s); // 使用 getline 函数读取一行字符串
cout << "请输入一个字符: ";
cin >> c;
int pos = s.find(c); // 使用 find 函数查找字符在字符串中首次出现的位置
if (pos == string::npos) {
cout << "-1" << endl;
} else {
cout << pos << endl;
}
return 0;
}
```
运行结果示例:
```
请输入一个字符串: Hello, world!
请输入一个字符: o
4
```
```
请输入一个字符串: Hello, world!
请输入一个字符: z
-1
```
相关问题
C + +输入一个字符串和一个字符查找并输出字符在字符串中首次出现的位置如果没有则输出-1
下面是 C++ 代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char ch;
cout << "请输入一个字符串:";
getline(cin, str); // 使用 getline() 函数读取一行字符串,避免空格被忽略
cout << "请输入一个字符:";
cin >> ch;
int pos = str.find(ch); // 在字符串中查找字符
if (pos == string::npos) {
cout << "没有找到该字符!" << endl;
} else {
cout << "该字符在字符串中第一次出现的位置为:" << pos << endl;
}
return 0;
}
```
运行程序后,输入一个字符串和一个字符,即可输出字符在字符串中首次出现的位置。如果没有找到该字符,则输出 `-1`。
输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1
好的,以下是 Python 代码实现:
```python
string = input("请输入一个字符串:") # 输入字符串
char = input("请输入一个字符:") # 输入字符
if char in string:
# 如果字符在字符串中出现过
index = string.index(char) # 获取字符在字符串中首次出现的位置
print("字符", char, "在字符串中首次出现的位置是:", index)
else:
# 如果字符没有出现过
print("字符", char, "在字符串中没有出现过")
print("-1")
```
希望能够帮到你!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)