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

Lazlo picture Lazlo · Sep 10, 2009 · Viewed 18.4k times · Source

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

Answer

Walt W picture Walt W · Sep 10, 2009

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.