AdBlock Detected

We provide high-quality source code for free. Please consider disabling your AdBlocker to support our work.

Buy me a Coffee

Saved Tutorials

No saved posts yet.

Press Enter to see all results

Trim Strings In c# (TrimStart, and TrimEnd)

By pushpam abhishek
Listen to this article
Trimming Strings

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.

Share this post

pushpam abhishek

About pushpam abhishek

Pushpam Abhishek is a Software & web developer and designer who specializes in back-end as well as front-end development. If you'd like to connect with him, follow him on Twitter as @pushpambhshk

Comments