输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1 编写cpp程序
时间: 2024-05-16 20:17:37 浏览: 14
以下是使用 C++ 实现的代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char ch;
int pos = -1;
cout << "请输入一个字符串:";
cin >> str;
cout << "请输入一个字符:";
cin >> ch;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == ch)
{
pos = i;
break;
}
}
if (pos == -1)
{
cout << "字符 " << ch << " 在字符串中未出现!" << endl;
}
else
{
cout << "字符 " << ch << " 在字符串中第一次出现的位置为:" << pos << endl;
}
return 0;
}
```
输入一个字符串和一个字符后,程序会遍历字符串中的每个字符,如果找到了与输入的字符相同的字符,就记录下该字符在字符串中的位置,并跳出循环。最后根据是否找到了字符来输出对应的结果。
相关问题
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)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)