首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不区分大小写的std::string.find()

不区分大小写的std::string.find()
EN

Stack Overflow用户
提问于 2010-07-01 02:28:28
回答 10查看 112.1K关注 0票数 76

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

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

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2010-07-01 02:35:34

您可以将std::search与自定义谓词一起使用。

代码语言:javascript
运行
复制
#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;
}
票数 82
EN

Stack Overflow用户

发布于 2013-11-07 23:08:04

新的C++11样式:

代码语言:javascript
运行
复制
#include <algorithm>
#include <string>
#include <cctype>

/// Try to find in the Haystack the Needle - ignore case
bool findStringIC(const std::string & strHaystack, const std::string & strNeedle)
{
  auto it = std::search(
    strHaystack.begin(), strHaystack.end(),
    strNeedle.begin(),   strNeedle.end(),
    [](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }
  );
  return (it != strHaystack.end() );
}

对std::搜索的解释可以在cplusplus.com上找到。

票数 63
EN

Stack Overflow用户

发布于 2010-07-01 02:34:19

为什么不在调用find()之前将两个字符串都转换为小写呢

tolower

注意:

对于internationalization issues.的长strings.

  • Beware,
  • 效率低下
票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3152241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档