TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# TrimEnd and TrimStart Methods

These C# examples use the TrimEnd and TrimStart methods on strings. TrimEnd removes trailing characters.

TrimEnd, TrimStart. TrimEnd removes ending characters from a string.

Suppose we have a string with trailing punctuation. We can use TrimEnd to remove these characters. TrimStart meanwhile removes from the start of a string.

TrimEnd. First, this example program loops through an array and trims its ending characters with TrimEnd. We use a string array. TrimEnd has similarities to Trim and Split. But it is used in different situations.

Trim

Note: The string array "items" here is used to show the results of TrimEnd. The TrimEnd method itself receives chars, not strings.

String ArrayChar

First: The example first creates a string array. Each string in the array is looped over with the foreach-loop.

Then: TrimEnd is called. It removes the question mark, period and comma from the string.

Based on:

.NET 4.5

C# program that uses TrimEnd

using System;

class Program
{
    static void Main()
    {
	// Our example string array.
	string[] items = new string[]
	{
	    "Who's there?",
	    "I am here..."
	};

	// Loop and call TrimEnd.
	foreach (string item in items)
	{
	    string trimmed = item.TrimEnd('?', '.', ',');
	    Console.WriteLine(item);
	    Console.WriteLine("    " + trimmed);
	}
	Console.ReadLine();
    }
}

Output

Who's there?
    Who's there
I am here...
    I am here

Signature. Let us examine the TrimEnd method in the .NET Framework. TrimEnd receives a params argument. This allows you to use a special syntax to send characters to it. You don't need an array, although you can use an array.

Signature of TrimEnd method: C#

string string.TrimEnd(params char[] trimChars)
Removes all trailing occurrences of a set of characters specified...

Params. Sometimes you want to send TrimEnd an array you create. This allows you to easily change how you call TrimEnd. In other words, you can send the method an entire array, or just several parameters separated by commas.

Params

Example of TrimEnd with many parameters: C#

string t = s.TrimEnd('?', '.', ',');

Example of TrimEnd with array: C#

char[] c = new char[]
{
    '?',
    '.',
    ','
};
string t = s.TrimEnd(c);

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

Note: We must provide a parameter to TrimStart, which contains the characters you want to Trim.

Tip: The characters can be anything. We do not need to use whitespace characters.

Whitespace

C# program that uses TrimStart

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."

Optimization. It is possible to develop custom implementations of TrimEnd that are faster than the version included in the .NET Framework. To do this, you can use a for-loop from the last index of the string.

For

In the loop, we count the number of characters to remove. And finally we return a substring using that value. Next we see a fast method that removes trailing punctuation from a string.

Remove, Trim Punctuation

Note: The optimized TrimTrailingChars method shown performed more than twice as fast as the TrimEnd method.

And: This could be a useful trick if you have a lot of trimming to do in an important program.

Optimized trim implementation: C#

static string TrimTrailingChars(string value)
{
    int removeLength = 0;
    for (int i = value.Length - 1; i >= 0; i--)
    {
	char let = value[i];
	if (let == '?' ||
	    let == '!' ||
	    let == '.')
	{
	    removeLength++;
	}
	else
	{
	    break;
	}
    }
    if (removeLength > 0)
    {
	return value.Substring(0, value.Length - removeLength);
    }
    return value;
}

Results

    Input string:
    const string input = "Dot Net Perls!?!...";
    Notes:
    TrimEnd version was called with a cached params array.

TrimTrailingChars: 34.87 ns
TrimEnd:           74.25 ns

Summary. TrimEnd and TrimStart can be used with array parameters. We used these methods to remove characters from the end and start of strings. These methods remove all characters specified until they hit a character they can't remove.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf