Trim String in C#


Trimming and Removing Characters from Strings

The String class provides Trim, TrimStart and TrimEnd methods to trim strings. The Trim method removes white spaces from the beginning and end of a string. The TrimEnd method removes characters specified in an array of characters from the end of a string and TrimStart method removes characters specified in an array of characters from the beginning of a string.

You can also use the Remove method to remove characters from a string. The Listing 2 code shows how to use these methods.

String str = " C# ";
Console.WriteLine("Hello{0}World!", str);
string trStr = str.Trim();
Console.WriteLine("Hello{0}World!", trStr );
str = "Hello World!";
char
[] chArr = {'e', 'H','l','o',' ' };
trStr = str.TrimStart(chArr);
Console.WriteLine(trStr);
str = "Hello World!";
char
[] chArr1 = {'e', 'H','l','o',' ' };
trStr = str.TrimEnd(chArr1);
Console.WriteLine(trStr);
string
MyString = "Hello Delta World!";
Console.WriteLine(MyString.Remove(5,10));


Read C# Strings  to learn more about strings in C#.

Up Next
    Ebook Download
    View all
    Learn
    View all