Trimming Strings
Here we learn about trimming string, 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.we have a habit of trimming them first. The .NET provides the Trim, TrimStart, and TrimEnd instance methods. TrimStart simply trims unnecessary whitespaces in the beginning, TrimEnd at the end, and Trim at the sides of the string.
string str1 = " Example ";
str1 = str1.Trim();
Console.WriteLine(str1);
Console.ReadLine();
Example
Trim methods have an overloaded version that accepts an array of characters So that you want to remove them in a string. The example below demonstrates this.
string str1 = "&&&&Hello***";
str1 = str1.Trim("&*".ToCharArray());
Console.WriteLine(str1);Console.ReadLine();
Hello
The string has "garbage" characters in the beginning and end of the string. also, 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.
Post A Comment:
0 comments: