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.
比较内存缓冲区和常量字符串的正确C ++方法是什么 - strcmp(buf,“sometext”)?我想避免因创建临时std :: string对象而导致不必要的内存复制。
Thanks.
5 个解决方案
#1
If you're just checking for equality, you may be able to use std::equal
如果您只是检查相等性,则可以使用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
当然,如果缓冲区小于文本,则需要额外的逻辑
#2
strcmp is good if you know the contents of your buffer. std::strncmp
might give you a little more security against buffer overflows.
如果你知道你的缓冲区的内容,strcmp是好的。 std :: strncmp可能会为缓冲区溢出提供更多安全性。
#3
strcmp
works fine, no copy is made. Alternatively, you could also use memcmp
. However, when in C++, why not use std::string
s?
strcmp工作正常,没有复制。或者,您也可以使用memcmp。但是,在C ++中,为什么不使用std :: strings?
#4
I would use memcmp, and as the last parameter, use the minimum of the 2 sizes of data.
我会使用memcmp,作为最后一个参数,使用2种大小的数据中的最小值。
Also check to make sure those 2 sizes are the same, or else you are simply comparing the prefix of the shortest one.
还要检查以确保这两个大小相同,否则您只是比较最短的大小的前缀。
#5
You may do it like,
你可以这样做,
const char* const CONST_STRING = "sometext";
strcmp(buf,CONST_STRING);
#1
If you're just checking for equality, you may be able to use std::equal
如果您只是检查相等性,则可以使用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
当然,如果缓冲区小于文本,则需要额外的逻辑
#2
strcmp is good if you know the contents of your buffer. std::strncmp
might give you a little more security against buffer overflows.
如果你知道你的缓冲区的内容,strcmp是好的。 std :: strncmp可能会为缓冲区溢出提供更多安全性。
#3
strcmp
works fine, no copy is made. Alternatively, you could also use memcmp
. However, when in C++, why not use std::string
s?
strcmp工作正常,没有复制。或者,您也可以使用memcmp。但是,在C ++中,为什么不使用std :: strings?
#4
I would use memcmp, and as the last parameter, use the minimum of the 2 sizes of data.
我会使用memcmp,作为最后一个参数,使用2种大小的数据中的最小值。
Also check to make sure those 2 sizes are the same, or else you are simply comparing the prefix of the shortest one.
还要检查以确保这两个大小相同,否则您只是比较最短的大小的前缀。
#5
You may do it like,
你可以这样做,
const char* const CONST_STRING = "sometext";
strcmp(buf,CONST_STRING);