-1

I need for a class a function which checks if a string is contained in another. Did I understand right that the STL function std::find for strings ignore lower and upper case (that is what I need)?

bilaljo
  • 358
  • 1
  • 6
  • 13

2 Answers2

2

find searches for an element equal to value

std::string::find iterates over the range and returns the position to the first element satisfying the condition or last is no match was found.

if you pass a substring contained in a larger string to the std::find function, the algorithm should return the position where the substring starts.

std::string::find is not case insensitive, it just iterates the container and checks if the substring is present

Adrian Costin
  • 418
  • 3
  • 12
1

std::string::find does not perform a case-insensitive search; it searches for an exact match. You would have to convert both the string to search and the search term to either lower or upper case first, and then use std::string::find.

However, there is another way you could do it with modern C++ (C++11 onward): use std::regex_search with the std::regex_constants::icase flag:

bool findCaseInsensitiveRegex(const std::string &completeString, const std::string &toSearch)
{
    std::regex pattern(toSearch, std::regex_constants::icase);
    return std::regex_search(completeString, pattern);
}

where toSearch is a regex made from the string to search for, and completeString is the complete string to search in.

Examples of both methods here.

jignatius
  • 6,304
  • 2
  • 15
  • 30