gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:13:45 37 4
gpt4 key购买 nike

我正在使用 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/37249092/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com