Team LiB
Previous Section Next Section

Trimming and Padding Strings

The string method provides three methods that allow you to trim spaces or 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.

Code Example: Trimming Spaces
Start example
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);
            }
      }
}
End example
Code Example: Padding Strings
Start example

using System;

namespace Client.Chapter_6___Strings
{
      class PaddingStrings
      {
            static void Main(string[] args)
            {
                  string MyString = "Hello World";

                  Console.WriteLine(MyString.PadLeft(5));
            }
      }
}
End example

Team LiB
Previous Section Next Section