This post will discuss how to remove leading and trailing spaces from a string in C#.

1. Using String.Trim() method

The standard solution to remove all whitespace characters from the beginning and end of the string is using the String.Trim() method. It returns a new string equal to the original string, but without leading and trailing spaces. Here’s an example of its usage.

Download  Run Code

2. Using String.TrimStart() method

The String.Trim() method removes all whitespaces from the start and end of the input string. If you need to remove only leading whitespace characters from a string, use the String.TrimStart() method. It returns a string with all whitespace characters removed from the start of the input string. Here’s what the code would look like:

Download  Run Code

3. Using String.TrimEnd() method

Alternatively, you can use the String.TrimEnd() method to remove only trailing whitespace characters from a string. It returns a string with all whitespace characters removed from the end of the input string.

Download  Run Code

 
Note that all the above methods do not modify the value of the original string object, and remove any leading/trailing characters for which the Char.IsWhiteSpace() method returns true.

That’s all about removing leading and trailing spaces from a string in C#.