c++ - 不区分大小写的 std::string.find()

标签 c++ string stl case-insensitive wstring

我正在使用 std::stringfind()测试一个字符串是否是另一个字符串的子字符串的方法。现在我需要同样东西的不区分大小写的版本。对于字符串比较,我总是可以求助于 stricmp()但似乎没有 stristr() .

我找到了各种答案,大多数建议使用 Boost在我的情况下,这不是一个选择。另外,我需要支持 std::wstring/wchar_t .有任何想法吗?

最佳答案

您可以使用 std::search 带有自定义谓词。

#include <locale>
#include <iostream>
#include <algorithm>
using namespace std;

// templated version of my_equal so it could work with both char and wchar_t
template<typename charT>
struct my_equal {
    my_equal( const std::locale& loc ) : loc_(loc) {}
    bool operator()(charT ch1, charT ch2) {
        return std::toupper(ch1, loc_) == std::toupper(ch2, loc_);
    }
private:
    const std::locale& loc_;
};

// find substring (case insensitive)
template<typename T>
int ci_find_substr( const T& str1, const T& str2, const std::locale& loc = std::locale() )
{
    typename T::const_iterator it = std::search( str1.begin(), str1.end(), 
        str2.begin(), str2.end(), my_equal<typename T::value_type>(loc) );
    if ( it != str1.end() ) return it - str1.begin();
    else return -1; // not found
}

int main(int arc, char *argv[]) 
{
    // string test
    std::string str1 = "FIRST HELLO";
    std::string str2 = "hello";
    int f1 = ci_find_substr( str1, str2 );

    // wstring test
    std::wstring wstr1 = L"ОПЯТЬ ПРИВЕТ";
    std::wstring wstr2 = L"привет";
    int f2 = ci_find_substr( wstr1, wstr2 );

    return 0;
}

关于c++ - 不区分大小写的 std::string.find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61107668/

相关文章:

c++ - 内存泄漏测试

c++ - 为什么容器需要const

c++ - 并行 STXXL vector 初始化

c++ - 显式实例化可变参数构造函数 : template-id does not match any template declaration

c++ - 组件之间如何有效通信?

python - 如何在Python中找到重复的字符串段?

c++ - 如何从 C++ 中的 std::cout 中删除一行?

java - 如何一次将一个字符串添加到 HashMap<Integer, List<String>> 中?

r - 如何在R中将一列拆分为多个(不相等)列

C++ 将一个 vector append 到另一个 vector