c++ - 检查字符串是否包含子字符串,不管大小写

标签 c++ string parsing substring

<分区>

假设我有一些字符串,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”子字符串。我可以通过某种论据来忽略大写吗?或者我应该完全使用其他东西吗?

最佳答案

有多种选择。

Using 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);

Using 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::string 分配给 ci_string 时需要使用 c_str 函数。

使用std::search使用自定义谓词

如文章 Case insensitive std::string.find() 中所建议.

关于c++ - 检查字符串是否包含子字符串,不管大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33950329/

相关文章:

objective-c - stringByTrimmingCharactersInSet : is not removing characters in the middle of the string

javascript - 解析 SVG 路径元素中的 d 属性

c++ - 基于开关的协程

c++ - 将 `std::string` 临时值传递给 `std::string_view` 参数是否安全?

c++ - string += s1 和 string = string + s1 之间的区别

Python字符串拆分,处理单引号

c++ - string::size_type 而不是 int

parsing - YACC/Bison中错误恢复产品的要求/限制是什么?

python - 如何解析 python 代码以识别全局变量用途?

c++ - RFID数据包