温馨提示×

c++中字符串的查找方法是什么

c++
小亿
85
2024-04-11 19:09:07
栏目: 编程语言

在C++中,字符串的查找可以通过使用find()方法来实现。find()方法通常用于在一个字符串中查找另一个子字符串的位置。例如:

#include <iostream>
#include <string>

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

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

    return 0;
}

在上面的例子中,我们首先定义了一个字符串str和一个子字符串subStr,然后使用find()方法在str中查找subStr的位置。如果找到了子字符串,则返回其位置;如果没找到,则返回std::string::npos

0