Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find string in vector of strings case insensitive c++

I have

std::vector<std::string> vec;
std::string myString; 

and I need to find out if myString is in vec using case insensitive comaprisons.

I know I can use

find(vec.begin(), vec.end(), myString) != vec.end())

to answer the question "is myString in vec?" but that will do case sensitive comparisons. I need case insensitive comparisons.

The position is not important, I just want to know if myString is in vec or not.

like image 669
Fredrik Persson Avatar asked Apr 08 '16 08:04

Fredrik Persson


1 Answers

You need to use std::tolower and std::find_if:

    std::vector<std::string> vec = {"ALF", "B"};
    std::string toSearch = "Alf";
    auto itr = std::find_if(vec.begin(), vec.end(),
                [&](auto &s) {
                    if ( s.size() != toSearch.size() )
                        return false;
                    for (size_t i = 0; i < s.size(); ++i)
                        if (::tolower(s[i]) == ::tolower(toSearch[i]))
                            return true;
                    return false;
                }
    );
    if ( itr != vec.end()) {
        std::cout << *itr << std::endl;
    }
like image 144
marcinj Avatar answered Sep 30 '22 06:09

marcinj