21xrx.com
2024-09-20 00:00:47 Friday
登录
文章检索 我的文章 写文章
C++中字符串如何查找子串
2023-07-05 05:46:50 深夜i     --     --
C++ 字符串 查找 子串 算法

在C++语言中,字符串是一种常用的数据类型。查找子串是字符串处理中一个重要的操作,在此介绍如何在C++中查找子串。

C++中查找子串有很多方法,下面我们介绍其中两种常用的方法。

方法一:使用find()函数查找子串

C++中的string类型提供了find()函数,可以方便地查找子串。该函数的基本语法如下:

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

其中,str是要查找的子串,pos是查找的起始位置,默认值为0。

例如,要在一个字符串中查找子串“hello”,可以使用如下代码:


string s = "world hello";

int pos = s.find("hello");

if(pos != string::npos)

  cout << "found at position: " << pos << endl;

else

  cout << "not found" << endl;

上述代码中,使用了find()函数查找“hello”子串。如果找到了,则返回该子串在字符串中的位置;否则返回字符串类型的静态常量npos,表示未找到。

方法二:使用substr()函数查找子串

C++中的string类型还提供了substr()函数,该函数用于获取字符串的子串。可以结合find()函数来实现查找子串的功能。该函数的基本语法如下:

string substr(size_t pos = 0, size_t len = npos) const;

其中,pos是要提取的子串的起始位置,len是要提取的子串的长度。

例如,要在一个字符串中查找子串“hello”,可以使用如下代码:


string s = "world hello";

int pos = s.find("hello");

if(pos != string::npos){

  string sub = s.substr(pos, 5);

  cout << "found sub string: " << sub << endl;

}

else

  cout << "not found" << endl;

上述代码中,使用了find()函数查找“hello”子串的位置,再结合substr()函数获取该子串。如果找到了,则返回该子串;否则返回未找到。

综上所述,C++中查找子串的方法有很多,常用的是使用find()函数和substr()函数结合来实现。这些函数能够帮助我们方便地进行字符串的处理,提高程序的效率和可读性。

  
  

评论区

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