21xrx.com
2024-09-19 09:14:20 Thursday
登录
文章检索 我的文章 写文章
C++中如何查找一个字符串中特定的字符串?
2023-06-24 12:54:09 深夜i     --     --
C++ 字符串 查找 特定字符串

在C++中,我们经常需要对字符串进行操作,其中一个常见的操作就是查找一个字符串中特定的字符串。为了实现这个功能,我们可以使用C++标准库中的string类提供的一些函数。本文将为您介绍C++中如何查找一个字符串中特定的字符串。

1. find函数

find函数是string类中用于查找子字符串的函数之一。其语法如下:

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

其中,第一个参数str表示要查找的子字符串;第二个参数pos表示搜索的起始位置,默认值为0。

例如,在以下代码中,我们使用find函数查找字符串s1中是否包含字符串s2:


#include <iostream>

#include <string>

using namespace std;

int main() {

 string s1 = "Hello, world!";

 string s2 = "world";

 

 // 在字符串s1中查找字符串s2

 int result = s1.find(s2);

 

 if (result != string::npos)

  cout << "找到了 else

  cout << "没找到" << endl;

 

 

 return 0;

}

输出结果为:


找到了,位置为:7

2. rfind函数

类似于find函数,rfind函数也是string类中用于查找子字符串的函数之一。其语法如下:

int rfind (const string& str, size_t pos = npos) const;

其中,第一个参数str表示要查找的子字符串;第二个参数pos表示搜索的起始位置,默认值为字符串的结尾,即npos。

该函数与find函数的最大区别在于,rfind是从字符串的末尾开始搜索的。例如,在以下代码中,我们使用rfind函数查找字符串s1中是否包含字符串s2:


#include <iostream>

#include <string>

using namespace std;

int main() {

 string s1 = "Hello, world!";

 string s2 = "world";

 

 // 在字符串s1中查找字符串s2

 int result = s1.rfind(s2);

 

 if (result != string::npos)

  cout << "找到了 else

  cout << "没找到" << endl;

 

 

 return 0;

}

输出结果与上例相同为:


找到了,位置为:7

3. substr函数

substr函数是string类中用于获取子串的函数之一。其语法如下:

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

其中,第一个参数pos表示子串的起始位置;第二个参数len表示子串的长度,默认值为字符串的结尾,即npos。

例如,在以下代码中,我们使用substr函数获取字符串s1中从位置7开始的子串:


#include <iostream>

#include <string>

using namespace std;

int main() {

 string s1 = "Hello, world!";

 

 // 获取从位置7开始的子串

 string s2 = s1.substr(7);

 

 cout << s2 << endl; // 输出结果为: "world!"

 

 return 0;

}

4. find_first_of函数和find_last_of函数

find_first_of函数和find_last_of函数是string类中用于查找字符集中任何一个字符的函数之一。其语法如下:

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

size_t find_last_of (const string& str, size_t pos = npos) const;

其中,第一个参数str表示要查找的字符集;第二个参数pos表示搜索的起始位置,默认值分别为0和npos。

例如,在以下代码中,我们使用find_first_of函数查找字符串s1中是否包含字符集"aeiou"中的任何一个字符:


#include <iostream>

#include <string>

using namespace std;

int main() {

 string s1 = "Hello, world!";

 

 // 查找字符串s1中是否包含字符集"aeiou"中的任何一个字符

 size_t result = s1.find_first_of("aeiou");

 

 if (result != string::npos)

  cout << "找到了 else

  cout << "没找到" << endl;

 

 

 return 0;

}

输出结果为:


找到了,位置为:1

这里我们使用了find_first_of函数,如果要使用find_last_of函数,只需将其替换即可。

综上,以上这些函数是C++标准库中string类中用于查找子字符串和字符集的函数,可以帮助我们非常方便地实现字符串的查找操作。希望此文为大家提供了一定的帮助。

  
  

评论区

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