21xrx.com
2024-09-20 00:40:09 Friday
登录
文章检索 我的文章 写文章
C++中使用string查找特定字符串
2023-07-05 12:00:34 深夜i     --     --
C++ string 查找 特定字符串

在C++编程中,使用string类型可以方便地进行字符串操作,比如查找特定字符串。对于需要在字符串中查找特定子串的问题,C++中提供了多种方法。

方法一:使用find()函数

C++ string类中的成员函数find()可以帮助我们查找一个特定的字符串或字符。这个函数可以接受一个参数,即需要查找的子串。find()函数会返回第一次出现该子串的位置,如果没有找到,返回string::npos。

如下示例代码:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = "Hello, world!";

  string target = "world";

  size_t position = str.find(target);

  if (position != string::npos)

  

    cout << "Find target at position " << position << endl;

  

  else

  

    cout << "Can not find target." << endl;

  

  return 0;

}

以上代码将输出:


Find target at position 7

方法二:使用substr()函数

C++中,string类的成员函数substr()可以用来从一个字符串中提取一个子串。可以使用find()函数查找指定子串在字符串中的位置,然后使用substr()函数从字符串中截取子串。

在以下示例代码中,我们使用find()函数来查找“world”在“Hello, world!”中的位置,然后使用substr()函数从子串中提取出该字符串。


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = "Hello, world!";

  string target = "world";

  size_t position = str.find(target);

  if (position != string::npos)

  {

    string result = str.substr(position, target.length());

    cout << "Result: " << result << endl;

  }

  else

  

    cout << "Can not find target." << endl;

  

  return 0;

}

以上代码将输出:


Result: world

总结

在C++中,使用string类型可以方便地进行字符串操作。通过find()函数或者substr()函数可以方便地查找或提取子串。这些函数的多样性,使得我们在字符串操作的时候有更多的选择和 flexibility。

  
  

评论区

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