Search code examples
c#arraysstringbytetrim

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


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


Solution

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