find

find用于在字符串中查找子字符串或字符的第一次出现。

如果 find 方法找到了子字符串,它返回子字符串的第一个字符的位置。

如果没有找到,它返回 std::string::npos,表示没有找到匹配项。

这个方法有几个重载版本,允许你查找不同类型的子串或字符,以及指定开始查找的位置。

以下是 find 方法的一些重载版本:

  • size_type find(const string& str, size_type pos = 0) const;

    在字符串中从位置 pos 开始查找子字符串 str

#include<bits/stdc++.h>
using namespace std;

int main()
{
    string baseStr = "Hello, World!";

    //size_t pos = baseStr.find("World", 0);
    int pos = baseStr.find("World");//也可以定义成int //缺省默认为0

/*
npos 和 -1 的解释
std::string::npos 是 std::string 类中定义的一个常量
表示 find 方法未找到子字符串时的返回值
它是 size_t 类型的最大值,不是 -1
由于 size_t 是一个无符号整数类型,当我们尝试以整数形式打印 std::string::npos 时,我们不会看到 -1,而是看到该类型能表示的最大值,通常是 18446744073709551615(对于 64 位系统)
然而,在条件表达式中使用 -1 来与 npos 比较似乎“有效”,是因为 -1 会被隐式转换为 size_t 类型,这种转换将 -1 转换为 size_t 能表示的最大值,即 npos。
因此,尽管 -1 在逻辑上不直接等同于 npos,但由于隐式类型转换,if (pos != -1) 这样的比较在实践中能够正确地判断 find 操作是否未找到匹配项。

不过,为了代码的可读性和可维护性,强烈推荐使用 std::string::npos 来检查 find 方法的返回值,而不是 -1。这样可以避免依赖于隐式类型转换的行为,使代码的意图更明确
*/

/*
当然 在写算法时可以不必这么严谨 怎么方便怎么来
直接用int定义pos -1判断即可
*/

    //if (pos != string::npos)
    if (pos != -1)
    {
        cout << "找到 'World' 在位置: " << pos << endl;//7
    }
    else {
        cout << "没找到 'World'!" << endl;
    }
    return 0;
}
  • size_type find(const char* s, size_type pos = 0) const;

    从位置 pos 开始查找由 s 指向的C风格字符串。

size_t pos = baseStr.find("World", 0);
if (pos != std::string::npos) {
    std::cout << "Found C-style 'World' at position: " << pos << std::endl;
} else {
    std::cout << "C-style 'World' not found!" << std::endl;
}

//这个例子和第一个例子实际上是等价的
//因为 "World" 在这里也被视为一个 C 风格的字符串。
  • size_type find(char c, size_type pos = 0) const;

    从位置 pos 开始查找字符 c

size_t pos = baseStr.find('W', 0);
if (pos != std::string::npos) {
    std::cout << "Found 'W' at position: " << pos << std::endl;
} else {
    std::cout << "'W' not found!" << std::endl;
}
//这里,'W' 是我们要查找的字符,从位置 0 开始搜索。

⬅️ 详情 🏠 00-刷题理模型 ➡️ strstr