检查字符串是否包含子字符串,而不考虑大小写

Checking if a string contains a substring, regardless of capitalization

本文关键字:字符串 不考虑 大小写 是否 包含 检查      更新时间:2023-10-16

假设我有一个字符串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::ifind_first

首先包括<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);

使用char_traits

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::字符串分配给ci_string时,需要使用c_str函数。

std::search与自定义谓词一起使用

正如文章中所建议的不区分大小写的std::string.find().