我想检查一个字符串是否是另一个字符串的严格子集。 为此,我使用了 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;
}
有没有更好的方法来解决这个问题?而不是也比较字符串的大小?
例子
- ABC 是 ABC 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/