views:

463

answers:

3

Hello :)

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

+6  A: 

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.

Walt W
null terminators have nothing to do with ASCII encoding. It seems @Lazlo has a fixed-sized byte array that holds a variable-lengthed ASCII encoded string, so the string has to be padded with null terminators to match the array size
dtb
@dtb: Right. Right right.
Walt W
Thank you :) I thought it was something like this, but didn't dare trying.
Lazlo
+3  A: 

They're not really spaces:

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

...should do the trick.

-Oisin

x0n
System.Encoding?
dtb
lol, thanks. updated.
x0n
+3  A: 

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