C++ str.find方法用法解析

avatar
作者
猴君
阅读量:0

在C++中,str.find()方法用于在字符串中查找特定的子字符串,并返回子字符串在原字符串中第一次出现的位置。该方法的语法如下:

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

其中,str表示要查找的子字符串,pos表示开始查找的位置,默认为0。

使用示例:

#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 << "Subtring found at position: " << found << std::endl;     } else {         std::cout << "Substring not found" << std::endl;     }      return 0; } 

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!