Search code examples
c#stringwhitespacetrimremoving-whitespace

Trim() and Replace(" ", "") not removing white space in C#


I am trying to write "text" into a file with

private void WriteToLogs(string text)
    {
        File.AppendAllText(todayMessageLog, $"({DateTime.Now}) Server Page: \"{text.Trim()}\"\n");
    }

The text comes out as this: "text (a bunch of white space)"

The text string is made up of these:

string username = e.NewClientUsername.Trim().Replace(" ", "");
string ip = e.NewClientIP.Trim().Replace(" ", "");

WriteToLogs($"{username.Trim().Replace(" ", "")} ({ip.Trim().Replace(" ", "")}) connected"); // NONE OF THESE WORKED FOR REMOVING THE WHITE SPACE

The "e" parameter comes from a custom EventArgs class in another namespace and NewClientIP and NewClientUsername are properties inside the class

As you can see, I tried with both Trim and Replace on both the strings themselves and the method but nothing removes the white space.


Solution

  • If the Trim() and Replace() methods do not work, the string is likely not padded with the usual white-space characters like SPACE or TAB, but something else. There are many other characters which can show up blank.

    Try printing the result with something like BitConverter.ToString(Text.Encoding.UTF8.GetBytes(text)). Spaces would show up as 20-20-20-..., but you will probably get something else.


    The white space shows up as 00, not 20, how can I remove it?

    Good. Use the argument to the Trim() method, like so:

    var text = "Blah\0\0\0\0";
    text.Length            → 8
    text.Trim('\0').Length → 4