Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim not working on null characters

I have a really bizarre problem with trim method. I'm trying to trim a string received from database. Here's my current method:

string debug = row["PLC_ADDR1_RESULT"].ToString();
SPCFileLog.WriteToLog(String.Format("Debug: ${0}${1}",debug,Environment.NewLine));
debug = debug.Trim();
SPCFileLog.WriteToLog(String.Format("Debug2: ${0}${1}", debug, Environment.NewLine));
debug = debug.Replace(" ", "");
SPCFileLog.WriteToLog(String.Format("Debug3: ${0}${1}", debug, Environment.NewLine));

Which produces file output as following:

Debug: $    $
Debug2: $    $
Debug3: $    $ 

Examining the hex codes in file revealed something interesting. The supposedly empty spaces aren't hex 20 (whitespace), but they are set as 00 (null?)

enter image description here

How our database contains such data is another mystery, but regardless, I need to trim those invalid (?) null characters. How can I do this?

like image 903
l46kok Avatar asked Sep 17 '15 06:09

l46kok


2 Answers

If you just want to remove all null characters from a string, try this:

debug = debug.Replace("\0", string.Empty);

If you only want to remove them from the ends of the string:

debug = debug.Trim('\0');

There's nothing special about null characters, but they aren't considered white space.

like image 156
Will Vousden Avatar answered Oct 23 '22 12:10

Will Vousden


String.Trim() just doesn't consider the NUL character (\0) to be whitespace. Ultimately, it calls this function to determine whitespace, which doesn't treat it as such.

Frankly, I think that makes sense. Typically \0 is not whitespace.

like image 43
Christian.K Avatar answered Oct 23 '22 12:10

Christian.K