C++程序设计输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1
时间: 2024-05-15 20:13:25 浏览: 13
下面是一个用 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`。如果找到了,就输出位置;否则就输出提示信息。
c++输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1
以下是使用C++实现的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
char c;
cout << "请输入一个字符串: ";
getline(cin, str);
cout << "请输入一个字符: ";
cin >> c;
int pos = str.find(c);
if (pos == -1) {
cout << "该字符没有在字符串中出现过" << endl;
} else {
cout << "该字符在字符串中首次出现的位置为: " << pos << endl;
}
return 0;
}
```
运行结果:
```
请输入一个字符串: hello world
请输入一个字符: o
该字符在字符串中首次出现的位置为: 4
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)