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

随声附和 提交于 2019-11-29 09:07:10
Walt W

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.

They're not really spaces:

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

...should do the trick.

-Oisin

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' });

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

In powershell, you can do this:

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