C + +输入一个字符串和一个字符查找并输出字符在字符串中首次出现的位置如果没有则输出-1
时间: 2024-05-16 11:17:21 浏览: 11
下面是 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`。
相关问题
C + +输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1。
下面是一个使用C++实现的示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char ch;
cout << "请输入一个字符串:";
getline(cin, str);
cout << "请输入一个字符:";
cin >> ch;
int pos = str.find(ch);
if (pos != string::npos)
{
cout << "字符 " << ch << " 在字符串中首次出现的位置为:" << pos << endl;
}
else
{
cout << "字符 " << ch << " 在字符串中没有出现!" << endl;
}
return 0;
}
```
在这个示例代码中,我们首先使用 `getline()` 函数从标准输入中获取一个字符串。然后,我们使用 `cin` 输入一个字符。接着,我们使用 `find()` 函数在字符串中查找字符,并将位置保存在 `pos` 变量中。如果 `pos` 不等于 `string::npos`,则说明字符在字符串中出现过,我们就输出该字符在字符串中首次出现的位置。如果 `pos` 等于 `string::npos`,则说明字符没有在字符串中出现过,我们就输出提示信息。
输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-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)
![](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)