c++

C++ str.find的参数及使用技巧

小樊
87
2024-08-08 23:11:37
栏目: 编程语言

在C++中,str.find()函数用于在字符串中查找特定子串的位置。其参数包括要查找的子串以及可选的起始位置。

语法如下:

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

其中,参数的含义如下:

使用示例:

#include <iostream>
#include <string>

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

    // 在字符串中查找子串的位置
    size_t found = str.find(sub);
    
    if (found != std::string::npos) {
        std::cout << "子串在字符串中的位置为:" << found << std::endl;
    } else {
        std::cout << "子串未找到" << std::endl;
    }
    
    return 0;
}

在上面的示例中,我们使用find()方法在字符串中查找子串"World"的位置,并输出结果。如果子串存在,则返回子串在字符串中的起始位置,否则返回std::string::npos。

0
看了该问题的人还看了