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.
- string text = "John";
- Console.WriteLine(text.PadLeft(10,'_'));
- Console.WriteLine(text.PadLeft(10, ' '));
- Console.WriteLine(text.PadLeft(10, '0'));
- Console.WriteLine(text.PadLeft(10, '*'));
- Console.ReadLine();
Out put
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.
- string text = "John";
- Console.WriteLine(text.PadRight(10,'_'));
- Console.WriteLine(text.PadRight(10, ' '));
- Console.WriteLine(text.PadRight(10, '0'));
- Console.WriteLine(text.PadRight(10, '*'));
- Console.ReadLine();
Out put
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
Post a Comment