Search code examples
c++c++20stdstringstl-algorithmstd-ranges

C++ std:: string starts_with/ends_with case insensitive versions?


C++20 added starts_with, ends_with to std::string.

Is there a nice way to get it to be case insensitive?

Note that perf matters so I do not want to lowercase/uppercase both strings(or std::min(len1, len2) parts of them).

Unlike regular <algorithm> algorithms starts_with has no overload with comparator so I see no nice way to do this.

And I kind of understand that 90+% of cases are case sensitive, and that member fns in C++ are avoided unless extremely useful... so I know why this limitation exists, I am just curious if something relatively readable can be hacked together in C++20 without me manually calling std::equal(or ranges version of equal) with custom comparator.


Solution

  • std::mismatch(s1.begin(), s1.end(), s2.begin(), s2.end(), <comparator>) will do what you want. You have to write the case-insensitve comparator, but I'm sure you can figure that out.