Sometimes, a user types unnecessary spaces that may cause certain errors. When accepting strings from a user, especially if the input came from a text box or similar controls, have a habit of trimming them first. .NET provides the TrimTrimStart, and TrimEnd instance methods. TrimStart simply trims unnecessary whitespaces in the beginning, TrimEnd at the end, and Trim on both sides of the string.

string str1 = "   Example   ";
str1 = str1.Trim();

Console.WriteLine(str1);
Example

The Trim methods have an overloaded version that accepts an array of characters that you want to remove in a string. The example below demonstrates this.

string str1 = "&&&&Hello***";
str1 = str1.Trim("&*".ToCharArray());

Console.WriteLine(str1);
Hello

Our string has “garbage” characters in the beginning and end of the string. We passed these garbage characters in our Trim method to remove them. Notice also that we use the ToCharArray method. The Trim method accepts a char array, and we passed a string, so to fulfill the requirements, we convert the string to character array by using the said method.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *