C++ string查找子串_C++ string find函数用法

std::string的find函数用于查找子串或字符,找到返回下标,否则返回npos;可指定起始位置进行多次查找;还提供rfind、find_first_of等变体函数实现不同查找需求。

在C++中,std::string 提供了 find() 成员函数,用于查找子串或字符在字符串中的位置。如果找到,返回首次出现的下标;如果未找到,返回 std::string::npos

find 函数基本用法

函数原型如下:

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:要查找的子串、C风格字符串或单个字符
  • pos:从哪个位置开始查找,默认从0开始

返回值:

  • 找到时返回匹配位置的索引(从0开始)
  • 未找到时返回 std::string::npos(通常为 -1 转换为无符号整数)

查找子串示例

以下代码演示如何使用 find 查找子串:

#include iostream>
#include
using namespace std;

int main() {
    string text = "Hello world, welcome to C++ programming";
    string pattern = "world";

    size_t pos = text.find(pattern);
    if (pos != string::npos) {
        cout     } else {
        cout     }
    return 0;
}

输出:

Found 'world' at position: 6

从指定位置开始查找

可以设置起始查找位置,用于查找多个匹配项:

size_t pos = 0;
while ((pos = text.find("o", pos)) != string::npos) {
    cout     ++pos; // 移动一位,避免重复匹配同一位置
}

这段代码会找出所有字符 'o' 的位置。

其他相关的查找函数

除了 find,string 还提供几个类似函数:

  • rfind():从后往前查找,返回最后一次出现的位置
  • find_first_of():查找参数中任意一个字符首次出现的位置
  • find_last_of():查找参数中任意字符最后一次出现的位置
  • find_first_not_of()find_last_not_of():查找不在指定字符集中的字符

例如:

string s = "apple,banana,cherry";
size_t p = s.find_first_of(","); // 找第一个逗号,返回5

基本上就这些。使用 find 时注意检查返回值是否为 npos,避免误用无效下标访问字符串。