假设我有一些字符串,str。
我要检查 str 是否包含关键字:“samples”
但是,“samples”可以是任何形式的大写,例如:“Samples”、“SamPleS”、“SAMPLES”。
这就是我正在尝试的:
string str = "this is a FoO test";
if (str.find("foo") != std::string::npos){
std::cout << "WORKS";
}
这不会检测“FoO”子字符串。我可以通过某种论据来忽略大写吗?或者我应该完全使用其他东西吗?
有多种选择。
首先包括<boost/algorithm/string/find.hpp>
和 <string>
.
然后使用ifind_first
如下。
std::string str = ...;
std::string subStr = ...;
boost::iterator_range<std::string::const_iterator> rng;
rng = boost::ifind_first(str, subStr);
struct ci_char_traits : public char_traits<char>
{
static bool eq(char c1, char c2) { return toupper(c1) == toupper(c2); }
static bool ne(char c1, char c2) { return toupper(c1) != toupper(c2); }
static bool lt(char c1, char c2) { return toupper(c1) < toupper(c2); }
static int compare(const char* s1, const char* s2, size_t n)
{
while( n-- != 0 )
{
if( toupper(*s1) < toupper(*s2) ) return -1;
if( toupper(*s1) > toupper(*s2) ) return 1;
++s1; ++s2;
}
return 0;
}
static const char* find(const char* s, int n, char a)
{
while(n-- > 0 && toupper(*s) != toupper(a))
{
++s;
}
return s;
}
};
typedef std::basic_string<char, ci_char_traits> ci_string;
然后就可以按如下方式使用了。
ci_string str = ...;
std::string subStr = ...;
auto pos = str.find(subStr.c_str());
请注意,问题在于调用 find 函数或将 ci_string 分配给 std::string 或将 std::string 分配给 ci_string 时需要使用 c_str 函数。
使用std::search
使用自定义谓词
如文章 Case insensitive std::string.find() 中所建议.