string::npos 是什么
时间: 2023-12-24 17:18:29 浏览: 25
`string::npos` 是一个常量,表示字符串中不存在指定的子串或字符时的返回值。它的值通常是一个大的正整数,比如在 `std::string` 类中,它的值为 `std::string::npos`,其定义为 `static const size_t npos = -1;`。
在字符串查找函数中,如果查找不到指定的子串或字符,就会返回 `string::npos`,通常用于判断查找结果是否有效。例如,在 `find()` 函数中,如果找到了指定的子串或字符,就会返回它在字符串中的位置,否则返回 `string::npos`。因此,我们可以使用以下代码来判断字符串中是否包含指定的子串:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
string subStr = "world";
size_t index = str.find(subStr);
if (index != string::npos) {
cout << "Found " << subStr << " at position " << index << endl;
} else {
cout << "Not found " << subStr << endl;
}
return 0;
}
```
在上面的代码中,我们使用 `find()` 函数查找子串 "world" 在字符串 "hello world" 中的位置,如果找到了就输出位置,否则输出提示信息。