C# How To Remove Whitespace
Remove Whitespace
Use the Trim() method to remove the spaces at the start and the end of a string:
Example
string text = " Hello World ";
string trimmed = text.Trim();
Console.WriteLine("[" + trimmed + "]");
To remove all spaces, also the ones between the words, use Replace() to replace each space with an empty string:
Example
string text = " Hello World ";
string noSpaces = text.Replace(" ", "");
Console.WriteLine("[" + noSpaces + "]");
Explanation:
The square brackets only show where the string starts and ends.Trim() keeps the space between the words. Use TrimStart() or TrimEnd() to remove spaces from only one side.