C# Tutorial C# Advanced C# References

C# String - Trim() Method



The C# Trim() method is used to removes all leading and trailing instances of a character(s) / whitespaces from the current string.

Note: This method can be overloaded by passing different type of arguments to it.

Syntax

//removes whitespaces
public string Trim();

//removes specified character
public string Trim(char trimChar);

//removes characters specified in the array
public string Trim(params char[] trimChars);

Parameters

trimChar Specify the character to remove.
trimChars Specify the array of characters to remove.

Return Value

Returns the trimmed version of the string.

Exception

NA.

Example:

In the example below, Trim() method returns the trimmed version of the string MyStr by removing whitespaces.

using System;

class MyProgram {
  static void Main(string[] args) {
    string MyStr = "    Hello World!.    ";
    string NewStr = MyStr.Trim();

    Console.WriteLine(NewStr); 
  }
}

The output of the above code will be:

Hello World!.

Example:

In the example below, Trim() method returns the trimmed version of the string MyStr by removing the specified characters in the char array.

using System;

class MyProgram {
  static void Main(string[] args) {
    string MyStr = ",*#Hello World!#@!";
    char[] CharToTrim = {',','*','#','@','!'};
    string NewStr = MyStr.Trim(CharToTrim);

    Console.WriteLine(NewStr); 
  }
}

The output of the above code will be:

Hello World

❮ C# String Methods