C++ 标准库 - <string>

C++ std::string::find() 从指定位置起查找子串(或字符)第一次出现的下标。找不到时返回 std::string::npos,不要把它当作有效下标参与算术。

原型

size_t find(const string& str, size_t pos = 0) const;
size_t find(const char* s, size_t pos = 0) const;
size_t find(char c, size_t pos = 0) const;

参数

  • str / s / c:要查找的内容。
  • pos:起始下标,默认为 0。

返回值

成功时返回首次匹配的下标;失败返回 npos。比较区分大小写。

示例

#include <iostream>
#include <string>

int main() {
    std::string s = "C++ string find";
    auto p = s.find("string");
    if (p != std::string::npos) {
        std::cout << p << std::endl;
    }
    if (s.find("xyz") == std::string::npos) {
        std::cout << "not found" << std::endl;
    }
    return 0;
}

输出:

4
not found

注意事项

失败时返回 npos,不可当作普通下标使用。判断应写 p != std::string::npos。从右向左查找用 rfind。

下一页介绍rfind:从右侧查找。