Trim a String in C#

Anytime a web form accepts user input that is destined for a database, it is (in the majority of the cases) important to trim string inputs. Without knowing, some users may cut and paste strings from one source to your form. For one reason or another, the cut and paste process may carry along unwanted extra spaces or other delimited not easily detected by the human eye. In C#, there are a few ways to handle this:

Let us assume string myString = “  Allied, agents   \r\n\r\n”;

myString.Trim()
This overload of the Trim method will remove whitespaces from both ends of the string. This is by far the most commonly used form of the method used to clean up user inputs. Often times, copy/pasted items contain a trailing space which can cause a lot of issues if not checked for.

String Output of “Allied, agents”.

myString.Trim(‘,’, ‘a’)
This overload of the Trim method will remove only the comma and lowercase letter a from either the beginning or the end of the string. Therefore, in this case, the string output will be exactly the same. Not that the letters specified are case sensitive. Additionally, you are allowed an unlimited number of characters.

String Output =  “  Allied, agents   \r\n\r\n”

TrimEnd(‘,’, ‘a’)
This overload does the exact same thing as Trim(‘,’,'a’), except that the letters are only trimmed from the end of the string.

TrimStart(‘,’, ‘a’)
This overload does the exact same thing as Trim(‘,’,'a’), except that the letters are only trimmed from the beginning of the string.

Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

Leave a Reply