Search code examples
c#trimremoving-whitespace

How to remove white spaces from sentence?


I want to remove all white spaces from string variable which contains a sentence. Here is my code:

string s = "This text contains white spaces";
string ns = s.Trim();

Variable "sn" should look like "Thistextcontainswhitespaces", but it doesn't(method s.Trim() isn't working). What am I missing or doing wrong?


Solution

  • The method Trim usually just removes whitespace from the begin and end of a string.

    string s = "     String surrounded with whitespace     ";
    string ns = s.Trim();
    

    Will create this string: "String surrounded with whitespace"

    To remove all spaces from a string use the Replace method:

    string s = "This text contains white spaces";
    string ns = s.Replace(" ", "");
    

    This will create this string: "Thistextcontainswhitespaces"