读取null结尾的字符串 [英] Reading a null-terminated string

查看:276
本文介绍了读取null结尾的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读从二进制文件的字符串。每个字符串是空终止的。编码是UTF-8。在python我只是读一个字节,检查它是否是0,则追加到一个字节数组,并继续读取字节,直到我看到了一个0。然后我转换字节数组转换为字符串,继续前进。所有的字符串被正确读取。

I am reading strings from a binary file. Each string is null-terminated. Encoding is UTF-8. In python I simply read a byte, check if it's 0, append it to a byte array, and continue reading bytes until I see a 0. Then I convert byte array into a string and move on. All of the strings were read correctly.

如何在C#中阅读?我不认为我有简单的附加字节奢侈品到一个数组,因为数组是固定大小。

How can I read this in C#? I don't think I have the luxury of simply appending bytes to an array since the arrays are fixed size.

推荐答案

可以无论是使用 列表<位>

You can either use a List<byte>:

List<byte> list = new List<byte>();
while(reading){ //or whatever your condition is
    list.add(readByte);
}

string output = Encoding.UTF8.GetString(list.ToArray());



或者你可以使用一个的 的StringBuilder

StringBuilder builder = new StringBuilder();

while(reading){
    builder.Append(readByte);
}

string output = builder.ToString();

这篇关于读取null结尾的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆