如何从 C# 字符串中获取以 null 结尾的字符串?
- 我正在与需要 null 终止字符串的服务器进行通信,
- 如何在 C# 中巧妙执行此操作?
- I am communicating with a server who needs null terminated string
- How can I do this smartly in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为聪明的方法就是简单地做。
然后将其转换为字节发送到服务器。
当然,您使用什么编码取决于服务器期望什么编码。
I think the smart way is to do it simply.
Then convert it into bytes to send to the server.
Of course what encoding you use depends on what encoding the server expects.
我假设您正在实现某种二进制协议(如果字符串以空结尾)。您使用的是
BinaryWriter
吗?默认的
BinaryWriter
以长度为前缀写入字符串。您可以更改该行为:然后您可以像这样编写任何字符串:
您可能需要根据您的需要调整
_encoding
位。当然,您可以根据可能需要传输的其他数据类型的特定需求来扩展该类,从而保持实际协议实现的整洁。您可能还需要自己的(非常相似)
BinaryReader
。I assume you're implementing some kind of binary protocol, if the strings are null terminated. Are you using a
BinaryWriter
?The default
BinaryWriter
writes strings as length prefixed. You can change that behavior:Then you can just write any string like this:
You may need to adjust the
_encoding
bit, depending on your needs.You can of course expand the class with specific needs for other data types you might need to transfer, keeping your actual protocol implementation nice and clean. You'll probably also need your own (very similar)
BinaryReader
.字符串已经以 null 结尾。尽管字符串本身不包含空字符,但在内存中,空字符始终跟在字符串后面。
但是,.NET 中的字符串是 unicode,因此它们在内存中存储为 UTF-16/UCS-2,并且服务器可能需要不同的编码,通常是 8 位编码。然后,您必须将字符串编码为字节数组,并在末尾放置一个零字节:
(zdata 数组在创建时全部用零填充,因此您不必实际将额外的字节设置为零。)
The strings are already null terminated. Although the string itself doesn't contain a null character, a null character always follows the string in memory.
However, strings in .NET are unicode, so they are stored as UTF-16/UCS-2 in memory, and the server might expect a different encoding, usually an 8 bit encoding. Then you would have to encode the string into a byte array and place a zero byte at the end:
(The zdata array is all filled with zeroes when creates, so you don't have to actually set the extra byte to zero.)
您将空字符添加到字符串末尾。 .NET 字符串可以包含空字符。
You add a null character to the end of the string. .NET strings can contain null characters.