What is Trim() method in C#?

The Trim() method in C# is used to remove any leading and trailing whitespace characters in a string. This means that it removes any whitespace that begins or ends a string.

Syntax

str.Trim()

Parameters

None.

Return value

It returns a string that contains no whitespace.

Code example

In the code example below, we will create some strings with whitespaces and remove those that start or ends them.

// creat class
class Trimmer
{
// main method
static void Main()
{
// create strings
string str1 = " Welcome to Edpresso! ";
string str2 = "Thedore Onyejiaku ";
string str3 = " a b c d ef ";
// trim strings
string a = str1.Trim();
string b = str2.Trim();
string c = str3.Trim();
// print returned values
System.Console.WriteLine(a);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
}
}

Free Resources