PadLeft & PadRight in C#

 

PadLeft and PadRight are two string methods available in c# to align a string value.

Let’s explain this with examples.

PadLeft

It returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length.

  1. string text = "John";
  2.  
  3.             Console.WriteLine(text.PadLeft(10,'_'));
  4.             Console.WriteLine(text.PadLeft(10, ' '));
  5.             Console.WriteLine(text.PadLeft(10, '0'));
  6.             Console.WriteLine(text.PadLeft(10, '*'));
  7.  
  8.             Console.ReadLine();
Out put

image

PadRight

It returns a new string that Left-aligns the characters in this instance by padding them on the right with a specified Unicode character, for a specified total length.

  1. string text = "John";
  2.  
  3.             Console.WriteLine(text.PadRight(10,'_'));
  4.             Console.WriteLine(text.PadRight(10, ' '));
  5.             Console.WriteLine(text.PadRight(10, '0'));
  6.             Console.WriteLine(text.PadRight(10, '*'));
  7.  
  8.             Console.ReadLine();

Out put

image

Usage

Certain systems may require a string to be of a fixed length, say 25 characters. If you only have 4 then you need to add 21 characters. Padleft will place your 4 characters on the very right hand of the string, adding enough pad characters to make it 25 characters (so, 21 spaces).

Happy Coding !!!!

Comments

Popular posts from this blog

Responsive Web Design

Affine Cipher in C#

Contract First Development in WCF 4.5