What is the correct C++ way of comparing a memory buffer with a constant string - strcmp(buf, "sometext")
? I want to avoid unnecessary memory copying as the result of creating temporary std::string objects.
Thanks.
What is the correct C++ way of comparing a memory buffer with a constant string - strcmp(buf, "sometext")
? I want to avoid unnecessary memory copying as the result of creating temporary std::string objects.
Thanks.
strcmp
works fine, no copy is made. Alternatively, you could also use memcmp
. However, when in C++, why not use std::string
s?
I would use memcmp, and as the last parameter, use the minimum of the 2 sizes of data.
Also check to make sure those 2 sizes are the same, or else you are simply comparing the prefix of the shortest one.
You may do it like,
const char* const CONST_STRING = "sometext";
strcmp(buf,CONST_STRING);
If you're just checking for equality, you may be able to use std::equal
#include <algorithms>
const char* text = "sometext";
const int len = 8; // length of text
if (std::equal(text, text+len, buf)) ...
of course this will need additional logic if your buffer can be smaller than the text