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 << "子串在字符串中的位置为:" << found << std::endl;     } else {         std::cout << "子串未找到" << std::endl;     }          return 0; } 

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

广告一刻

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