How do I remove extra spaces between words in C#

removing whitespace from the end of a string C#
removing whitespace from the end of a string C#

How do I remove extra spaces between words in C#?

If you have several strings that you need to trim whitespaces from,  I only need to remove them from the end. They are being used for company and individual names, so it’s okay for spaces in the middle of the string.

You could use Trim() or if you want to apply to just the end TrimEnd()

string sValue = "  test IODOCS ";
sValue  = sValue.Trim();
sValue  = sValue.TrimEnd();
//Result "test IODOCS"
How do I remove extra spaces between words in C#
How do I remove extra spaces between words in C#

C# Trim() is a string method. This method is commonly used to remove all leading and trailing whitespace characters from the current String object.

  • Trim() Removes all current string’s leading and trailing white-space characters. Trim(Char) Removes all leading and trailing instances of a character from the current string.
  • Trim(Char[]) Removes all leading and trailing occurrences of a set of characters specified in an array from the current string.

Look at the following example that I quoted from Microsoft’s documentation page.

char[] charsToTrim = { '*', ' ', '\''};
string banner = "* Much Ado About Nothing *";
string result = banner.Trim(charsToTrim);
Console.WriteLine("Trimmmed\n   {0}\nto\n   '{1}'", banner, result);

// The example displays the following output:
//       Trimmmed
//          * Much Ado About Nothing *
//       to
//          'Much Ado About Nothing'

String.TrimEnd: trims selected characters from the end of the string only.

message.TrimStart(): will trim from the left side of the string variable.

message.Trim(): will trim from both sides of the string variable.

Note: You should pay attention to the documentation in MSDN: there was a breaking change to the behavior of this method, so the actual behavior depends on the version of .NET Framework you are targetting.

4/5 - (7 votes)