Case-sensitive comparison
Case-sensitive comparison is simple.
However, we need to use the sv
literal to make a std::string_view
that can contain null characters. Some of its constructors could also handle it, but no solution is as concise as sv
literals (or s
for std::string
).
using namespace std::string_view_literals;
// prior to C++17, you can use std::string and "..."s
std::string_view s1 = "Abcd\0abcd"sv;
std::string_view s2 = "Abcd\0cccc"sv;
bool eq = s1 == s2; // false
std::string_view
already 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::equal
or std::equal
.
#include <cctype> // std::tolower
#include <algorithm> // std::ranges::equal or std::equal
// C++20
bool eq = std::ranges::equal(s1, s2, [](unsigned char a, unsigned char b) {
return std::tolower(a) == std::tolower(b);
});
// legacy
bool eq = std::equal(std::begin(s1), std::end(s1), std::begin(s2), std::end(s2),
[](unsigned char a, unsigned char b) {
return std::tolower(a) == std::tolower(b);
});
Note: it's important that the lambda accepts unsigned char
, not char
; std::tolower
doesn't work properly if we input negative values, and char
may be negative.
Note: std::tolower
doesn't handle unicode strings. See also Case-insensitive string comparison in C++ for more robust solutions.
memcmp
can compare two arbitrary memory buffers. – Hokeypokeyconst char*
,char[]
orstd::string
? – Haemoid"Abcd\0abcd"s
, actually, yourstd::string
doesn't have\0
in the middle. – Renault