C# Remove White Spaces from Edges of String

To remove white spaces at both edges of String in C#, call Trim() method on the string instance. If no arguments are passed to String.Trim() method, then any white space characters at the edges of given string will be removed.

Reference to C# String.Trim() method.

Example

In the following program, we have taken a string " abcd " with leading and trailing white spaces. We will remove the white spaces from the edges of the string using String.Trim() method.

C# Program

</>
Copy
using System;
  
class Example {
    static void Main(string[] args) {
        String str = "  abcd ";
        String result = str.Trim();
        Console.WriteLine($"Original String  : \"{str}\"");
        Console.WriteLine($"Trimmed String   : \"{result}\"");
    }
}

Output

Original String  : "  abcd "
Trimmed String   : "abcd"

Conclusion

In this C# Tutorial, we have learned how to remove leading and trailing white spaces of a given string using Trim() method.