std::string find函数查找失败的返回值
时间: 2023-11-20 08:07:30 浏览: 104
如果使用的是 C++ 标准库中的 `std::string` 类型的成员函数 `find()` 进行字符串查找,当查找失败时,它会返回 `std::string::npos`,它是一个静态成员常量,通常被定义为 `-1`,表示没有找到匹配的子串。因此,可以通过判断 `find()` 的返回值是否等于 `std::string::npos` 来判断查找是否成功。
相关问题
std::string 查找字符串
您可以使用C++中的`std::string::find()`函数来查找一个字符串中是否包含另一个字符串。
例如,如果您想要查找字符串`str`是否包含子字符串`subStr`,您可以使用以下代码:
```cpp
std::string str = "Hello World";
std::string subStr = "World";
if (str.find(subStr) != std::string::npos) {
std::cout << "Substring found in the string!" << std::endl;
} else {
std::cout << "Substring not found in the string." << std::endl;
}
```
在上述代码中,`std::string::find()`函数返回子字符串`subStr`在`str`中的位置。如果子字符串不在字符串中,则返回`std::string::npos`。因此,我们可以检查返回值是否等于`std::string::npos`来判断是否找到了子字符串。
std::string::npos
`std::string::npos`是一个常量,表示`std::string::find()`函数的返回值,当`std::string::find()`函数无法找到匹配的子字符串时,将返回该常量。`npos`的值通常为-1,因此可以用于检查字符串中是否存在子字符串。例如,以下代码将在字符串`s`中查找子字符串`foo`,并检查是否找到了该子字符串:
```c++
std::string s = "Hello, world!";
if (s.find("foo") != std::string::npos) {
std::cout << "Found\n";
} else {
std::cout << "Not found\n";
}
```
如果`s`中包含子字符串`foo`,则输出`Found`,否则输出`Not found`。