#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"
Advertisement