C# TrimStart

String type

TrimStart removes leading characters. Sometimes strings have characters at their starts that are not needed. The C# TrimStart method provides a handy way to remove as many characters of the specific values as required.

This C# example program uses the TrimStart method on string data.

Example

First here we see the TrimStart method, which is separate from Trim but works very similarly. You have to provide a parameter to TrimStart, which contains the characters you want to Trim. The characters can be anything, even non-whitespace characters.

Program that uses TrimStart [C#]

using System;

class Program
{
    static void Main()
    {
	string text = "\t, again and again.";       // Trim this string
	char[] arr = new char[] { '\t', ',', ' ' }; // Trim these characters

	text = text.TrimStart(arr);
	Console.WriteLine(text);
    }
}

Output

"again and again."
Note

Description. The string we are trimming contains three characters at its start we need to remove: a tab character, a comma, and a space. The char[] array declared contains the three characters we want to remove. These can be in any order. They are looped over in Trim's implementation.

Using the TrimStart method. TrimStart is called. It receives the array we declared, and is an instance method on the string we want to trim. Finally, the output is printed; it does not contain the unwanted characters at the beginning.

Performance

Performance optimization

Unfortunately, the TrimStart method is not heavily optimized. In specific situations, you will likely be able to write character-based iteration code that can outperform it. This is because an array must be created to use TrimStart in this context, while custom code would not necessarily require an array at all. However, for quickly-developed applications, the TrimStart method is useful.

Summary

The C# programming language

We looked at the TrimStart instance method on the string type in the C# programming language, which provides a way to remove a series of characters of the specified values in a single function call. The TrimStart method is an effective string mutation method and it can simplify certain algorithms—particularly those in text-based string processing applications.

Trim String String Type
.NET