比较缓冲区与C ++中的const char *

时间:2009-05-18 13:33:56

标签: c++ string comparison

将内存缓冲区与常量字符串strcmp(buf, "sometext")进行比较的正确C ++方法是什么?我希望避免因创建临时std :: string对象而导致不必要的内存复制。

感谢。

5 个答案:

答案 0 :(得分:4)

如果你知道你的缓冲区的内容,strcmp是好的。 std::strncmp可能会为缓冲区溢出提供更多安全保护。

答案 1 :(得分:3)

如果您只是检查是否平等,则可以使用std::equal

#include <algorithms>

const char* text = "sometext";
const int len = 8; // length of text

if (std::equal(text, text+len, buf)) ...

当然,如果缓冲区小于文本

,则需要额外的逻辑

答案 2 :(得分:1)

strcmp工作正常,没有复制。或者,您也可以使用memcmp。但是,在C ++中,为什么不使用std::string s?

答案 3 :(得分:1)

我会使用memcmp,并且作为最后一个参数,使用2种大小的数据中的最小值。

同时检查以确保这2个尺寸相同,否则您只是比较最短的尺寸的前缀。

答案 4 :(得分:0)

你可以这样做,

const char* const CONST_STRING = "sometext";

strcmp(buf,CONST_STRING);