c++

C++ str.find的用法及示例代码

小樊
93
2024-08-08 23:17:38
栏目: 编程语言

在C++中,string.find()函数用于在字符串中查找子字符串第一次出现的位置。它返回子字符串第一次出现的位置,如果没有找到,则返回string::npos

以下是string.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 << std::endl;
    } else {
        std::cout << "未找到子字符串" << std::endl;
    }

    return 0;
}

在上面的示例代码中,str.find(subStr)函数将查找子字符串"World"在字符串"Hello, World!"中第一次出现的位置,并将结果存储在变量found中。如果找到了子字符串,则打印子字符串在字符串中的位置;否则打印未找到子字符串。

需要注意的是,string::npos是一个特殊的常量,表示未找到子字符串时的返回值。

0
看了该问题的人还看了