This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Trimming Non-Whitespace Characters from Strings

Often string data is received through a user interface or integration system. This data may include additional characters to the main information, either as a prefix or suffix. Using the String class's Trim method, the unwanted characters can be removed.

Basic Trimming

When accepting input it is impossible to guarantee that string information is formatted exactly as anticipated. It is a common problem for textual information to be surrounded by additional spaces. These may appear at the start or the end of the string. To remove leading or trailing spaces, the trim methods of the string class can be executed.

Three trim methods are available. The simplest is Trim, which removes all leading and trailing spaces from a string. Alternatively, the TrimStart and TrimEnd methods can be utilised to remove spaces from either the start or end of the string respectively. In each case, the method is executed without any parameters.

Trimming Non-Whitespace Characters

Each of the three Trim methods can be used to remove leading and trailing characters other than spaces. The three methods all include a parameter that accepts an array of characters. If any of the characters provided are present at the start or end of the string, they can be deleted using the appropriate method.

To demonstrate, try executing the following code:

char[] toTrim = new[] {' ', '_' };
string test = "___ BlackWasp ___";

Console.WriteLine(test.Trim(toTrim));       // Outputs "BlackWasp"
Console.WriteLine(test.TrimStart(toTrim));  // Outputs "BlackWasp ___"
Console.WriteLine(test.TrimEnd(toTrim));    // Outputs "___ BlackWasp"
1 April 2008