用c++编写程序,输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有,则输出-1。
时间: 2023-11-22 19:56:42 浏览: 34
以下是用 C++ 实现的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
char ch;
cout << "Enter a string: ";
getline(cin, str);
cout << "Enter a character: ";
cin >> ch;
int pos = str.find(ch); // 查找字符在字符串中首次出现的位置
if (pos == string::npos) { // 如果没有找到
cout << "-1" << endl;
} else {
cout << pos << endl;
}
return 0;
}
```
代码中使用了 `std::string` 类型和 `std::string::find` 方法来查找字符在字符串中首次出现的位置。如果找到了,则输出该位置;否则,输出 `-1`。
相关问题
C++程序设计输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1
下面是一个用 C++ 实现的例子:
```cpp
#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 << "-1" << endl;
} else {
cout << pos << endl;
}
return 0;
}
```
运行程序后,会提示用户输入一个字符串和一个字符,然后查找并输出字符在字符串中首次出现的位置。如果没有找到该字符,则输出-1。例如,输入字符串 "hello world" 和字符 'w',则输出结果为 6。如果输入字符串 "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);
cout << "请输入一个字符:";
cin >> ch;
int pos = str.find(ch);
if (pos != string::npos) {
cout << "字符\"" << ch << "\"在字符串中首次出现的位置是:" << pos << endl;
} else {
cout << "字符串中没有出现\"" << ch << "\"这个字符!" << endl;
}
return 0;
}
```
使用 `string` 类型的 `find()` 函数查找字符在字符串中首次出现的位置,如果没有找到则返回 `string::npos`。如果找到了,就输出位置;否则就输出提示信息。
相关推荐
![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)