Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C++

Idiom #133 Case-insensitive string contains

Set boolean ok to true if string word is contained in string s as a substring, even if the case doesn't match, or to false otherwise.

#include <algorithm>
#include <cctype>
auto ok = std::search(std::begin(s), std::end(s), std::begin(word), std::end(word),
    [](auto c, auto d){
        return std::tolower(c) == std::tolower(d);
    }
) != std::end(s);
ok = s.Contains(word, StringComparison.CurrentCultureIgnoreCase);

The existing C# implementation is overly naïve in cultures such as Turkey which use different capitalisation rules to English. This implementation respects the current culture's capitalisation rules.

In some situations it may be more appropriate to use the InvariantCultureIgnoreCase or OrdinalIgnoreCase options instead.

New implementation...