📜  C++ find()查找子字符串(1)

📅  最后修改于: 2023-12-03 15:13:54.120000             🧑  作者: Mango

C++ find()查找子字符串

在C++中,可以使用find()方法来查找一个字符串中是否存在一个子字符串。本文将介绍C++中的find()方法的用法和示例。

find()方法概述

find()方法是C++中string类的一个方法,它用于在一个字符串中查找一个子字符串。如果找到了该子字符串,返回该子字符串在原字符串中的位置;如果未找到,返回一个特殊值string::npos。

find()方法的语法如下:

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

其中,第一个参数为要查找的子字符串,可以是一个string对象、一个C风格的字符串(char*),或者一个字符;第二个参数是起始查找的位置,可以不指定,默认为0。

示例

以下是几个使用find()方法查找子字符串的示例:

示例1:查找字符串中是否包含另一个字符串
#include <iostream>
#include <string>

using namespace std;

int main() {
    string s1 = "hello world";
    string s2 = "world";
    if (s1.find(s2) != string::npos) {
        cout << "s1 contains s2" << endl;
    } else {
        cout << "s1 does not contain s2" << endl;
    }
    return 0;
}

输出结果为:

s1 contains s2
示例2:查找字符串中第一次出现的位置
#include <iostream>
#include <string>

using namespace std;

int main() {
    string s1 = "hello world";
    string s2 = "world";
    size_t pos = s1.find(s2);
    if (pos != string::npos) {
        cout << "s2 first appears at position " << pos << " in s1" << endl;
    } else {
        cout << "s2 does not appear in s1" << endl;
    }
    return 0;
}

输出结果为:

s2 first appears at position 6 in s1
示例3:从字符串的某个位置开始查找
#include <iostream>
#include <string>

using namespace std;

int main() {
    string s1 = "hello world hello";
    string s2 = "hello";
    size_t pos = s1.find(s2, 7);
    if (pos != string::npos) {
        cout << "s2 first appears at position " << pos << " in s1 starting from position 7" << endl;
    } else {
        cout << "s2 does not appear in s1 starting from position 7" << endl;
    }
    return 0;
}

输出结果为:

s2 first appears at position 12 in s1 starting from position 7
示例4:查找字符串中的某个字符
#include <iostream>
#include <string>

using namespace std;

int main() {
    string s1 = "hello world";
    char c = 'l';
    size_t pos = s1.find(c);
    if (pos != string::npos) {
        cout << "the character " << c << " first appears at position " << pos << " in s1" << endl;
    } else {
        cout << "the character " << c << " does not appear in s1" << endl;
    }
    return 0;
}

输出结果为:

the character l first appears at position 2 in s1
总结

本文介绍了C++中使用find()方法查找子字符串的方法和示例。无论是查找某个字符串中是否包含另一个字符串,还是查找字符在字符串中的位置,都可以使用该方法。在实际编程中,经常会用到该方法,建议熟练掌握。