string::find()函数怎么用
时间: 2023-06-04 10:03:08 浏览: 67
可以使用string::find()函数来查找一个字符串中是否包含某个子字符串,此函数的语法如下:
```c++
size_t find(const string& str, size_t pos = 0) const noexcept;
```
其中,第一个参数是被查找的子字符串,第二个参数表示从哪个位置开始查找。如果查找成功,该函数会返回子字符串在原字符串中的位置,如果查找失败,该函数会返回string::npos。
下面是一个使用例子:
```c++
#include <iostream>
#include <string>
int main()
{
std::string str = "hello world";
std::string sub = "world";
size_t pos = str.find(sub);
if (pos != std::string::npos) {
std::cout << "找到了,位置是:" << pos << std::endl;
} else {
std::cout << "没找到" << std::endl;
}
return 0;
}
```
该程序的输出结果是:
```
找到了,位置是:6
```
相关问题
std::string::find失败
在C++中,std::string::find函数是用来查找字符串中是否包含另一个子字符串的函数。当该函数找到匹配的子字符串时,它会返回该子字符串在原字符串中的位置;如果没有找到匹配的子字符串,该函数会返回std::string::npos。
std::string::npos是一个静态常量,其值为-1。当std::string::find无法找到匹配的子字符串时,它将返回这个特殊的值。
如果std::string::find函数返回std::string::npos,则意味着在原字符串中没有找到匹配的子字符串。这可能是因为要查找的子字符串不存在于原字符串中,也可能是因为搜索起始位置不正确。在这种情况下,您可以检查返回值是否等于std::string::npos来判断搜索是否成功。
std::string find函数查找失败的返回值
如果使用的是 C++ 标准库中的 `std::string` 类型的成员函数 `find()` 进行字符串查找,当查找失败时,它会返回 `std::string::npos`,它是一个静态成员常量,通常被定义为 `-1`,表示没有找到匹配的子串。因此,可以通过判断 `find()` 的返回值是否等于 `std::string::npos` 来判断查找是否成功。
相关推荐
![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)