Trim C# String

In this article we will discuss about how to trim the string in C#.
  • 3955

Trimming a string is removing spaces and/or special characters from a string. A sting can be trimmed from the left side, the right side and also both sides.

The TrimStart method is used to trim a string from the starting and TrimEnd method is used to trip as string from the end.

Here is a complete example:

Console.WriteLine("TrimString");
string firstName = "Mahesh";
string lastName = "Chand";
string age = "33";
string authorInfo = " Author "+ firstName + " " + lastName + " is "
    + age.ToString() + " years old.  ";
Console
.WriteLine("Original string:{0}", authorInfo);
Console.WriteLine("Lengh:{0}", authorInfo.Length);
string trimmedString = authorInfo.Trim();
Console
.WriteLine("Trimmed string:{0}", trimmedString);
Console.WriteLine("Lengh:{0}", trimmedString.Length);      
// Trim End
string trimmedLeftString = authorInfo.TrimStart();
Console
.WriteLine("Trimmed left string:{0}", trimmedLeftString);
Console.WriteLine("Lengh:{0}", trimmedLeftString.Length);       
// Trim Start
string trimmedRightString = authorInfo.TrimEnd();
Console
.WriteLine("Trimmed right string:{0}", trimmedRightString);
Console.WriteLine("Lengh:{0}", trimmedRightString.Length);       
char[] charsToTrim = { '*', ' '};
string charString = " ** Author " + firstName + " "
    + lastName + " is " + age.ToString() + " years old. *** ";
string charTrimmed = charString.Trim(new char[] {'*', ' '});
Console
.WriteLine("Char Trimmed string:{0}", charTrimmed);
Console.WriteLine("Lengh:{0}", charTrimmed.Length);


Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.