21xrx.com
2024-09-20 00:42:34 Friday
登录
文章检索 我的文章 写文章
C++:搜索字符串B在字符串A中的位置
2023-07-10 08:52:54 深夜i     --     --
C++ string search position substring

在C++编程中,经常需要对字符串进行处理。其中一个常见操作是搜索字符串B在字符串A中的位置。下面我们来学习如何在C++中实现这个操作。

首先,我们可以使用C++标准库中的函数find()来查找字符串B在字符串A中的位置。该函数的语法如下:


string::size_type pos = strA.find(strB);

其中,strA是要搜索的字符串A,strB是要查找的字符串B,pos是B在A中的位置。

需要注意的是,如果字符串B不存在于字符串A中,函数find()将返回一个特殊的值string::npos。因此,可以使用以下方法来判断是否找到了字符串B:


if (pos != string::npos)

  // found

else

  // not found

例如,下面的代码可以输出字符串B在字符串A中的位置,如果字符串B不存在于字符串A中,则输出“Not Found”:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string strA = "hello world";

  string strB = "world";

  string::size_type pos = strA.find(strB);

  if (pos != string::npos)

    cout << "Found at position " << pos << endl;

   else

    cout << "Not Found" << endl;

  

  return 0;

}

以上就是在C++中搜索字符串B在字符串A中的位置的方法。希望对大家有帮助!

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复