简体   繁体   English

来自字节数组的字符串不会在C#中被修剪?

[英]String from byte array doesn't get trimmed in C#?

I have a byte array similar to this (16 bytes): 我有一个类似于此的字节数组(16字节):

71 77 65 72 74 79 00 00 00 00 00 00 00 00 00 00

I use this to convert it to a string and trim the ending spaces: 我用它来将它转换为字符串并修剪结束空格:

ASCIIEncoding.ASCII.GetString(data).Trim();

I get the string fine, however it still has all the ending spaces. 我得到的字符串很好,但它仍然有所有结束空格。 So I get something like "qwerty.........." (where dots are spaces due to StackOverflow). 所以我得到类似"qwerty.........."东西(其中点是StackOverflow的空格)。

What am I doing wrong? 我究竟做错了什么?

I also tried to use .TrimEnd() and to use an UTF8 encoding, but it doesn't change anything. 我也尝试使用.TrimEnd()并使用UTF8编码,但它不会改变任何东西。

Thanks in advance :) 提前致谢 :)

You have to do TrimEnd(new char[] { (char)0 }); 你必须做TrimEnd(new char[] { (char)0 }); to fix this. 解决这个问题。 It's not spaces - it's actually null characters that are converted weirdly. 它不是空格 - 它实际上是奇怪转换的空字符。 I had this issue too. 我也有这个问题。

They're not really spaces: 他们不是真正的空间:

System.Text.Encoding.ASCII.GetString(byteArray).TrimEnd('\0')

...should do the trick. ......应该做的伎俩。

-Oisin -Oisin

Trim by default removes only whitespace , where whitespace is defined by char.IsWhitespace . 默认情况下修剪仅删除空格 ,其中空格由char.IsWhitespace定义。

'\\0' is a control character, not whitespace. '\\0'是控制字符,不是空格。

You can specify which characters to trim using the Trim(char[]) overload: 您可以使用Trim(char[])重载指定要修剪的Trim(char[])

string result = Encoding.ASCII.GetString(data).Trim(new char[] { '\0' });

在powershell中,您可以这样做:

$yourString.TrimEnd(0x00)

Why try to create the string first and trim it second? 为什么要先尝试创建字符串然后再修剪它? This could add a lot of overhead (if the byte[] is large). 这可能会增加很多开销(如果byte []很大)。

You can specify index and count in the GetString(byte[] bytes, int index, int count) overload. 您可以在GetString(byte[] bytes, int index, int count)重载中指定indexcount

int count = data.Count(bt => bt != 0); // find the first null
string result = Encoding.ASCII.GetString(data, 0, count); // Get only the characters you want

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

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