#104 – Functions to Trim Leading and Trailing Characters from A String

You can use the Trim function to trim leading and trailing whitespace characters from a string.

 string s = "  The core phrase ";  // 2 leading spaces, 1 trailing
 s = s.Trim();     // s = "The core phrase"

Once again, the function does not change the original string, so you have to assign the result to some string.

You can also give Trim a list of characters that you want trimmed:

 string s = "  {The core phrase,} ";
 s = s.Trim(new char[] {' ','{',',','}'});     // s = "The core phrase"
 s = " {Doesn't {trim} internal stuff }";
 s = s.Trim(new char[] {' ', '{', '}'});      // s = "Doesn't {trim} internal stuff"

Finally, you can trim stuff from the start or end of the string with TrimStart and TrimEnd.

 string s = "{Name}";
 char[] braces = new char[] {'{', '}'};
 string s2 = s.TrimStart(braces);    // s2 = "Name}"
 s2 = s.TrimEnd(braces);             // s2 = "{Name"
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #104 – Functions to Trim Leading and Trailing Characters from A String

  1. firemystdl says:

    For anyone interested in speed and benchmarks, this blog posting investigates the fastest way to Trim() strings:
    http://cc.davelozinski.com/c-sharp/fastest-way-to-trim-strings
    using multiple techniques.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: