Case insensitive std::string.find()

前端 未结 10 1980
挽巷
挽巷 2020-11-27 02:47

I am using std::string\'s find() method to test if a string is a substring of another. Now I need case insensitive version of the same thing. For s

10条回答
  •  离开以前
    2020-11-27 03:26

    Also make sense to provide Boost version: This will modify original strings.

    #include 
    
    string str1 = "hello world!!!";
    string str2 = "HELLO";
    boost::algorithm::to_lower(str1)
    boost::algorithm::to_lower(str2)
    
    if (str1.find(str2) != std::string::npos)
    {
        // str1 contains str2
    }
    

    or using perfect boost xpression library

    #include 
    using namespace boost::xpressive;
    ....
    std::string long_string( "very LonG string" );
    std::string word("long");
    smatch what;
    sregex re = sregex::compile(word, boost::xpressive::icase);
    if( regex_match( long_string, what, re ) )
    {
        cout << word << " found!" << endl;
    }
    

    In this example you should pay attention that your search word don't have any regex special characters.

提交回复
热议问题