c++ - 如何检查字符串是否是另一个字符串的真子集

标签 c++ string

我想检查一个字符串是否是另一个字符串的严格子集。 为此,我使用了 boost::contains我比较字符串的大小如下:

#include <boost/algorithm/string.hpp>
#include <iostream>

using namespace std;
using namespace boost::algorithm;

int main()
{
  string str1 = "abc news";
  string str2 = "abc";
  //strim strings using boost
  trim(str1);
  trim(str2);
  //if str2 is a subset of str1 and its size is less than the size of str1 then it is strictly contained in str1
  if(contains(str1,str2) && (str2.size() < str1.size()))
  {
    cout <<"contains" << end;
  }
  return 0;
}

有没有更好的方法来解决这个问题?而不是也比较字符串的大小?


例子

  • ABCABC NEWS
  • 的真子集
  • ABC 不是 ABC
  • 的真子集

最佳答案

我会使用以下内容:

bool is_substr_of(const std::string& sub, const std::string& s) {
  return sub.size() < s.size() && s.find(sub) != s.npos;
}

这仅使用标准库,并首先进行大小检查,这比 s.find(sub) != s.npos 便宜。

关于c++ - 如何检查字符串是否是另一个字符串的真子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30029869/

相关文章:

python - 有没有什么方法可以在Python中打乱字符串?

python - 拆分和连接字符串

c++ - 构建过程的阶段是什么

c++ - 删除 STL vector 中的条目

c++ - 检测录音中的不同声音/来源

c++如何通过指向类的指针删除类

python - 如何删除 ^M

java - 从文件中分割字符串换行符

c++ - 字符串生成

Android Studio - 2个字符串数组到 ListView