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/3152241/

相关文章:

c++ - 如何遍历 STL 集直到倒数第二个元素?

c++ - 使用 std::min_element() 时保存函数计算

c++ - 跳转到 lldb 中的行号

c++ - 删除字母代码出错(C++)

javascript - 删除特定分隔符后面的字符串的最后部分

c++ - 如何递增表示为字符串的 IP 地址?

C++:我应该通过数组实现堆栈/队列/双端队列以提高性能吗?

C++ - 对象的平滑加速和减速

c++ - 更改数组中的对象但不更改对象的数量 - C++

c++ - SFML 组合可绘制对象