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

社会主义新天地 提交于 2019-11-28 02:28:53

问题


I have a byte array similar to this (16 bytes):

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).

What am I doing wrong?

I also tried to use .TrimEnd() and to use an UTF8 encoding, but it doesn't change anything.

Thanks in advance :)


回答1:


You have to do 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.




回答2:


They're not really spaces:

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

...should do the trick.

-Oisin




回答3:


Trim by default removes only whitespace, where whitespace is defined by char.IsWhitespace.

'\0' is a control character, not whitespace.

You can specify which characters to trim using the Trim(char[]) overload:

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



回答4:


Why try to create the string first and trim it second? This could add a lot of overhead (if the byte[] is large).

You can specify index and count in the GetString(byte[] bytes, int index, int count) overload.

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



回答5:


In powershell, you can do this:

$yourString.TrimEnd(0x00)


来源:https://stackoverflow.com/questions/1402622/string-from-byte-array-doesnt-get-trimmed-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!