简体   繁体   English

如何将终止 NUL 字符 \x00 转换为字符串?

[英]How to get the terminating NUL character \x00 into a string?

How would i get a string with the null character \x00 since \x00 is also the terminating character?我如何得到一个带有 null 字符 \x00 的字符串,因为 \x00 也是终止字符?

I really do need it for part of my program.我真的需要它作为我程序的一部分。

The string I need is "\x00\x00\x00\x00".我需要的字符串是“\x00\x00\x00\x00”。 Is there some special syntax for it?它有一些特殊的语法吗? What is it?它是什么?

In C++ the std::string class will work while including NUL characters.在 C++ 中, std::string class 将在包含 NUL 字符时工作。

However:然而:

  • The c_str() function will fail. c_str() function 将失败。
  • The constructors that read a const char* will fail.读取const char*的构造函数将失败。

You would probably be better served by using a std::vector<char> .使用std::vector<char>可能会更好地为您服务。

You're doing it correctly.你做对了。 You just need to avoid interpreting a null as the ending character.您只需避免将 null 解释为结束字符。

But then how do you know where it ends?但是你怎么知道它在哪里结束呢? I don't know;我不知道; you could store the length somewhere instead.您可以将长度存储在某个地方。

You can have a "normal" string which embeds nulls, but at the first null any function that expects a null-terminated string will stop processing it;可以拥有一个嵌入空值的“普通”字符串,但在第一个 null 任何期望以空值结尾的字符串的 function 都会停止处理它; thus, you need to use counted strings.因此,您需要使用计数字符串。

C++ std::string being a type of counted string, you can use it to carry around these strings. C++ std::string是一种计数字符串,您可以使用它来携带这些字符串。 Keep in mind however that you shouldn't convert it back to a C string when using it (ie don't use the c_str() method), otherwise you will be back to square one.但是请记住,在使用它时不应该将它转换回 C 字符串(即不要使用c_str()方法),否则您将回到原点。

However, to have more specific suggestions, you should explain a bit better what are you trying to achieve.但是,要获得更具体的建议,您应该更好地解释您想要实现的目标。

If it is a std::string you want, you can get any size you want如果它是你想要的 std::string,你可以得到任何你想要的大小

std::string s(10, '\0');

gives you a string with 10 nul characters.给你一个包含 10 个 nul 字符的字符串。

std::string str("\0\0\0\0", 4);

This constructor tells string to use the 1st 4 characters of the char*, without interpreting any \0 characters as null.此构造函数告诉字符串使用 char* 的前 4 个字符,而不将任何 \0 字符解释为 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM