CopyPastehas never been so tasty!

Pad String in C#

by anonymous

  • 0
  • 0
  • 0
72 views

Orignal Source:http://codingvilla.com/pad-string-csharp-single-article-613.aspx

 

Pad String in C#:

 

Padding a string means you can add spaces or characters to the right or left side of string. C# provides us two types of pad methods that are PadRight and PadLeft.

 

PadRight:

 

PadRight method is used to add spaces or characters on the right side of strings. You can pad any type of character by using PadRight method not only spaces. Let us consider an example program in which we declare an array of strings. Then iterate this array in foreach loop and get output. In the output the spaces are added on right side of string and position of string is on left side of added spaces because PadRight method adds spaces on Right side.

 

 

Code:

 

 

classPadRight_Method

  

 {

 staticvoid Main(string[] args)

        {

try

            {

 

string[] a ={"cat","poodle","lizard","frog","photon"};

 

 

 

// Output array.

foreach (string s in a)

                {

Console.Write(s.PadRight(15));

 

                }

Console.Read();

            }

catch (Exception exce)

            {

Console.WriteLine(exce);

            }

    }

 

    }

 

 

Output:

 

 

Cat           poodle                     lizard                frog                  photon

 

 

PadLeft:

 

PadLeftmethod is used to add spaces or characters on the left side of strings. You can pad any type of character by using PadLeft method not only spaces. Let us consider an example program in which we have declared an array of strings. Then we have iterated this array in foreach loop and get output. In the output the spaces are added on left side of string and position of string is on right side of added spaces because PadLeft method adds spaces on left side.

 

 

Code:

 

 

classPadLeft_Method

    {

staticvoid Main(string[] args)

        {

try

            {

 

string[] a ={"cat","poodle","lizard","frog","photon"};

 

 

 

// Output array.

foreach (string s in a)

                {

Console.Write(s.PadLeft(15));

//     Console.WriteLine("noun");

                }

Console.Read();

            }

catch (Exception exce)

            {

Console.WriteLine(exce);

            }

    }

 

}

 

 

Output:

 

 

Cat         poodle lizard             frog                  photon

 

Add A Comment: