CopyPastehas never been so tasty!

Justify & Align Strings in C#

by anonymous

  • 0
  • 0
  • 0
79 views

Orignal Source:http://codingvilla.com/justify-align-strings-csharp-single-article-612.aspx

 

Justify & Align Strings in C#:

 

Usually we need four types of string alignment that are Left align, right align center align and justify. And we choose that alignment which we need.

 

And for alignment C# provides us the following methods:

 

Trim, PadLeft and PadRight

 

Trim Method:

 

Trim method is used to remove spaces from starting and ending of a string. It returns a string with removed spaces.

 

Pad Method:

 

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 method is used to add spaces or characters on the right side of strings. You can pad any type of character as well as spaces by using PadRight method. PadLeft method is used to add spaces or characters on the left side of strings. You can pad any type of character as well as spaces by using PadLeft method.

 

Code:

 

classjustifying_and_align_string

    {

staticvoid Main(string[] args)

        {

try

            {

stringstr = "test";

string str1 = "Paper"; ;

stringst = "  This is an example string. ";

Console.WriteLine("Original string: " +str);

 

// Pad on left with spaces.

str = str.PadLeft(10);

Console.WriteLine("|" + str + "|");

 

// Pad on right with spaces.

                str1 = str1.PadRight(20);

Console.WriteLine("|" + str1 + "|");

 

// Call Trim instance method.

// This returns a new string copy.

st = st.Trim();

 

Console.WriteLine(st);

Console.Read();

            }

catch(Exceptionexce)

            {

Console.WriteLine(exce);

            }

        }

 

    }

 

Output:

 

 

|test|

 

|Paper|

 

 

This is an example string.

 

Add A Comment: