Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare buffer with const char* in C++

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.

like image 356
jackhab Avatar asked Jan 24 '23 14:01

jackhab


1 Answers

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

like image 64
Ferruccio Avatar answered Jan 27 '23 13:01

Ferruccio