简体   繁体   中英

String.Trim() doesn't remove whitespaces

I have a small program that loads or saves a byte array from or to a file. In this byte array is contained a string, for example:

byte[] header = new byte[64]; //the actual array is larger, but this is for explaining purposes only...
string savedString = Encoding.ASCII.GetString( header, 0, 64 );

because the string I used to write to the file was only 5 characters long, the "savedString" loads to be "string " etc However, in this situation, I had no worries, I just added

.Trim();

to

Encoding.ASCII.GetString( header, 0, 64 );

yet this still doesn't cut the string down to the right size upon loading, so I'm guessing the padding is not made up of whitespaces?

Thanks.

The byte array is initially filled with zeros, and the the character that represents is a control character, and not a whitespace character. Try specifically trimming these zero-characters like this:

savedString.Trim('\0');

For example:

byte[] header = new byte[64];
header[0] = (byte)'A';
string savedString = Encoding.ASCII.GetString(header, 0, 64);

var output1 = savedString.Trim();
Console.WriteLine("{0} ({1})", output1, output1.Length); // A□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□ (64)
var output2 = savedString.Trim('\0');
Console.WriteLine("{0} ({1})", output2, output2.Length); // A (1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM