44

对于常规 C 字符串,空字符'\0'表示数据结束。

怎么样std::string,我可以有一个嵌入空字符的字符串吗?

4

4 回答 4

45

是的,您可以在std::string.

例子:

std::string s;
s.push_back('\0');
s.push_back('a');
assert(s.length() == 2);

注意:std::string' 的c_str()成员将始终在返回的 char 缓冲区中附加一个空字符;但是,std::stringdata()成员可能会也可能不会将空字符附加到返回的字符缓冲区。

小心操作符+=

需要注意的一件事是不要在 RHS 上使用operator+=a 。char*它只会累加到空字符。

例如:

std::string s = "hello";
s += "\0world";
assert(s.length() == 5);

正确的方法:

std::string s = "hello";
s += std::string("\0world", 6);
assert(s.length() == 11);

存储二进制数据更常见于使用 std::vector

通常,它更常用std::vector于存储任意二进制数据。

std::vector<char> buf;
buf.resize(1024);
char *p = &buf.front();

这可能更常见,因为std::string'data()c_str()成员返回 const 指针,因此内存不可修改。使用 &buf.front() 您可以直接修改缓冲区的内容。

于 2010-05-16T22:43:40.733 回答
7

是的。std::string 只是一个vector<char>好处。

但是,小心不要将这样的野兽传递给.c_str()在 0 处调用和停止的东西。

于 2010-05-16T22:44:26.940 回答
0

You can, but why would you want to? Embedding NUL in an std::string is just asking for trouble, because functions to which you pass an std::string may very well use it's c_str() member, and most will assume that the first NUL indicates the end of the string. Hence this is not a good idea to do. Also note that in UTF-8, only '\0' will result in a 0, so even for i18n purposes, there is no justification for embedding NULs.

于 2010-05-16T22:56:40.203 回答
-3

是的,这是有效的。

字符串中间可以有一个空字符。

但是,如果您使用带有 ac 字符串函数的 std::string 中间有一个空字符,那么您在未定义的行为小镇 - 并且没有人愿意在那里!!!:

 int n = strlen( strWithNullInMiddle.c_str() ); // Boom!!!
于 2010-05-16T22:43:37.430 回答