温馨提示×

str.find在C++字符串查找中的作用

c++
小樊
91
2024-08-08 23:18:38
栏目: 编程语言

在C++中,str.find()函数用于在字符串中查找指定的子字符串,并返回子字符串第一次出现的位置。如果找到了指定的子字符串,则返回子字符串的索引位置;如果未找到指定的子字符串,则返回npos(string::npos)值。该函数的语法如下:

size_t find(const string& str, size_t pos = 0) const noexcept;

其中,str为要查找的子字符串,pos为从哪个位置开始查找,默认为0(从字符串的起始位置开始查找)。如果指定了pos参数,则从指定的位置开始查找子字符串。

以下是一个示例:

#include <iostream>
#include <string>

using namespace std;

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

    size_t found = str.find(subStr);
    if (found != string::npos) {
        cout << "Substring found at position: " << found << endl;
    } else {
        cout << "Substring not found" << endl;
    }

    return 0;
}

在上面的示例中,首先定义了一个字符串str和一个要查找的子字符串subStr。然后使用find()函数在字符串str中查找子字符串subStr,并将返回的位置存储在found变量中。最后根据found的值判断是否找到了子字符串。

0