I want to compare two strings s1 and s2 and both strings can have null characters in between. I want both case sensitive and insensitive compare like strcmp and strcasecmp. Suppose my strings are:
std::string s1="Abcd\0abcd"
std::string s2="Abcd\0cccc"
Currently, I'm doing strcmp(s1.c_str(), s2.c_str()) and strcasecmp(s1.c_str(), s2.c_str()) but strcasecmp and strcmp end up giving equal in this case and skip the comparison after \0.
Any libraries I can use to compare these strings.
Case-sensitive comparison
Case-sensitive comparison is simple. However, we need to use the
svliteral to make astd::string_viewthat can contain null characters. Some of its constructors could also handle it, but no solution is as concise assvliterals (orsforstd::string).std::string_viewalready doesn't care about null characters in the string, so you can use the overloaded==operator.In general, you should avoid C functions like
strcmp; there are much better alternatives in C++ that don't require null-terminated strings.Case-insensitive comparison
Case-insensitive comparison is slightly more difficult, but can be easily done with
std::ranges::equalorstd::equal.Note: it's important that the lambda accepts
unsigned char, notchar;std::tolowerdoesn't work properly if we input negative values, andcharmay be negative.Note:
std::tolowerdoesn't handle unicode strings. See also Case-insensitive string comparison in C++ for more robust solutions.