The string method provides three methods that allow you to trim spaces or characters from a string:
The TrimStart method allows you to trim the leading empty or space characters from a string.
The TrimEnd method removes trailing spaces from the end of a string.
The Trim method allows you to remove specific characters from a string.
If you want to add spaces or a specific character to the beginning or end of a string, you can use the PadLeft or PadRight method. The only parameter that these methods take is the number of characters with which to pad the existing string. This is the simplest way to pad a string. An overloaded version of the method allows you to add a parameter that defines the padding character.
The following examples demonstrate trimming spaces from a string and adding spaces to the beginning of a string.
using System;
namespace Client.Chapter_6___Strings
{
class TrimmingSpaces
{
static void Main(string[] args)
{
string MyString = " Hello, World ! ";
//Removes whitespace from the front of the string
MyString.TrimStart();
Console.WriteLine(MyString);
//Removes whitespace from the end of the string
MyString.TrimEnd();
Console.WriteLine(MyString);
//Removes the "!" character
MyString.Trim(char.Parse("!"));
Console.WriteLine(MyString);
}
}
}