Hit enter after type your search item

What is C# Trim method?

The Trim() method of strings is used to remove the leading and trailing spaces from the specified string. You may use the trim() method in the following ways:

  • Without providing any arguments i.e. String.Trim()

This will remove unwanted whitespace from the left and right of the specified string.

  • Providing argument (See the example in the last section) i.e. Trim(Char[])

This way allows removing the specified leading and trailing character(s)

Besides, C# also has methods for removing the whitespace from the start or end of the specified string. These methods are:

  • TrimEnd()
  • TrimStart()

You may also remove the specified number of characters based on index position in the string. The method for this purpose is:

  • Remove

See the examples below for learning how to remove leading and trailing spaces along with specifying other characters in the Trim() C# method.

The example of using Trim method

In the first example of C# Trim() method, we will remove whitespace from the left and right of the string. I intentionally added leading and trailing spaces in a string and then used the Trim() method as follows:


c# trim

You can see the last string is displayed without whitespace.

Note: The original string remains the same after using the Trim() method, as such the string in C# is immutable.

An example of removing space from left/start

The following example uses the TrimStart() method for removing the spaces from the left side of the string only. For showing that only the spaces from start are removed, I have concatenated another string to see spaces still exist on the right side of the string:


c# trim_start

Removing trailing whitespace example

Similarly, you may use the TrimEnd() method for removing the spaces from the right side of the string. The example below shows how:


c# trim_end

Using the Trim method with multiple parameters

In the above examples, we only removed leading and trailing whitespace by using the Trim, TrimStart, and TrimEnd methods.

You may also use Trim method for removing the other characters by providing parameters – as mentioned in the introductory section of this tutorial.

The general way of using the Trim with parameters:

Trim(Char[])

In the example below, we have specified an array of characters to be trimmed from the specified string. The Trim() method will remove any leading space, comma, forward slash, x, y, and z i.e.

char[] ArrTrim = {‘ ‘,’,’, ‘/’, ‘x’, ‘y’, ‘z’};

See the code and output below:


The result:

Original:  xy C# cool yz

After Trim:C# Cool

Note that the Trimming will occur as long as a character in the parameter list is encountered in the specified string. As long as some other character is found, the trim function is terminated.

This div height required for enabling the sticky sidebar