21xrx.com
2025-03-30 02:35:26 Sunday
文章检索 我的文章 写文章
C++实现判断字符串包含关系
2023-06-27 13:47:22 深夜i     25     0
C++ 字符串 包含关系 实现 判断

在C++中,判断一个字符串是否包含另一个字符串可以使用标准库中的函数find()来实现。find()函数返回被查找字符串的第一个出现位置,如果找不到则返回一个特定值。通过对返回值进行判断,就可以得知是否包含另一个字符串。

下面是使用find()函数判断两个字符串包含关系的示例代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str1 = "hello world";
  string str2 = "world";
  size_t pos = str1.find(str2);
  if (pos != string::npos)
  
    cout << "str1 contains str2" << endl;
  
  else
  
    cout << "str1 does not contain str2" << endl;
  
  return 0;
}

在上面的示例代码中,我们首先定义了两个字符串str1和str2,分别为"hello world"和"world"。然后使用find()函数在str1中查找str2的位置,将返回值赋值给pos变量。如果pos不等于string::npos,即代表找到了str2,说明str1包含str2;否则,不包含。

除了使用find()函数,C++中还有其他方法可以判断字符串包含关系,比如使用正则表达式、使用字符串的substr()函数等等。根据实际情况,选择适合的方法即可。

  
  

评论区