获取包含Null终止字符串的字符串的长度

时间:2016-09-03 11:24:46

标签: c++ string null-terminated

我正在使用XOR加密,因此当我要解密我的字符串时,我需要获取该字符串的长度。

我试过这样的方式:

string to_decode = "abcd\0lom";
int size = to_decode.size();

或以这种方式:

string to_decode = "abcd\0lom";
int size = to_decode.lenght();

两者都错了,因为字符串包含\0。 那么我怎样才能拥有正确的琴弦长度呢?

3 个答案:

答案 0 :(得分:2)

问题在于初始化,而不是尺寸。如果使用构造函数取const char *,它会将该参数解释为NUL终止的字符串。因此,您的std::string仅使用字符串abcd初始化。

您需要使用基于范围的构造函数:

const char data[] = "abcd\0lom";
std::string to_decode(data, data + (sizeof data) - 1);  // -1 to not include terminating NUL

[Live example]

但是,要小心这些字符串。虽然std::string可以完全处理嵌入式NUL,但c_str()的结果将表现为"截断"就所有以NUL终止的API而言。

答案 1 :(得分:1)

初始化std::string时,如果中间有\0,则会丢失所有数据。如果您考虑一下,std::string只是char*的包装器,并且会被空终止\0终止。如果\0string中没有任何意义,那么你可以逃避它,就像这样:

string to_decode = "abcd\\0lom";

,大小为9.否则,您可以使用std::vector的容器(例如:char)进行数据存储

答案 2 :(得分:0)

正如其他人所说,问题是代码使用了const char*的构造函数,而且只复制到\0。但是,通过一个非常奇怪的巧合,std::string有一个构造函数可以处理这种情况:

const char text[] = "abcd\0lom";
std::string to_decode(text, sizeof(text) - 1);
int size = to_decode.size();

构造函数将复制您告诉它的任意数量的字符。

相关问题