Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

2.23. Pruning Characters from the Headand/or Tail of a String

Problem

You have a string with a specific set of characters, such as spaces, tabs, escaped single/double quotes, any type of punctuation character(s), or some other character(s), at the beginning and/or end of a string. You want a simple way to remove these characters.

Solution

Use the Trim, TrimEnd, or TrimStart instance methods of the String class:

string foo = "--TEST--";
Console.WriteLine(foo.Trim(new char[1] {'-'}));            // Displays "TEST"

foo = ",-TEST-,-";
Console.WriteLine(foo.Trim(new char[2] {'-',','}));        // Displays "TEST"

foo = "--TEST--";
Console.WriteLine(foo.TrimStart(new char[1] {'-'}));       // Displays "TEST--"

foo = ",-TEST-,-";
Console.WriteLine(foo.TrimStart(new char[2] {'-',','}));   // Displays "TEST-,-"

foo = "--TEST--";
Console.WriteLine(foo.TrimEnd(new char[1] {'-'}));         // Displays "--TEST"

foo = ",-TEST-,-";
Console.WriteLine(foo.TrimEnd(new char[2] {'-',','}));     // Displays "-,-TEST"

Discussion

The Trim method is most often used to eliminate whitespace at the beginning and end of a string. In fact, if you call Trim without any parameters on a string variable, this is exactly what would happen. The Trim method is overloaded to allow you to remove other types of characters from the beginning and end of a string. You can pass in a char[] containing all the characters that you want removed from the beginning and end of a string. Note that if the characters contained in this char[] are located somewhere in ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata