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()

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.

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.

3.8/5 - (6 votes)