ARTICLE

Trim String in C#

Posted by Mahesh Chand Articles | String in C# August 21, 2010
This code snippet shows how to trim a string in C#.
Reader Level:

Trimming and Removing Characters from Strings

TheString class provides Trim, TrimStart and TrimEnd methods to trim strings. The Trim method removes white spaces from the beginning and endof 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#.

Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.