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)?
-
6why do you think `std::find` would be case-insensitive? – 463035818_is_not_an_ai Jul 20 '20 at 09:19
-
3No you understand wrong. – john Jul 20 '20 at 09:21
-
Use `std::find_if` instead and supply a function to do the case insensitive comparison. – john Jul 20 '20 at 09:23
-
your question is kind of vague, what exactly are you tryinjg to do? – Adrian Costin Jul 20 '20 at 09:26
-
To use @john solution this thread may help https://stackoverflow.com/q/36494584/6865932 – anastaciu Jul 20 '20 at 09:27
-
In recommend you to provide full description of your problem, to avoid misunderstanding. Issue can be more complex then you can imagine, for example if your string is UTF-8 encoded. – Marek R Jul 20 '20 at 09:38
-
Also, why did you not try this before asking? – kesarling He-Him Jul 20 '20 at 09:42
2 Answers
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

- 418
- 3
- 12
-
1`std::find` returns an iterator and finds characters in strings, not substrings. Maybe you refer to `std::string::find`(but that also returns no pointer) – 463035818_is_not_an_ai Jul 20 '20 at 09:50
-
1also not an iterator to the last element is returned, but an iterator one past the last element if the element could not be found – 463035818_is_not_an_ai Jul 20 '20 at 09:51
-
yes, it returns std::string::npos, and yes it is std::string::find @idclev463035818, thank you for the correction. aren't iterators just a generalization of pointers though ? – Adrian Costin Jul 20 '20 at 10:57
-
vehicle is a generalization for car, but yet planes are no cars ;) – 463035818_is_not_an_ai Jul 20 '20 at 11:30
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.

- 6,304
- 2
- 15
- 30