C# String Formatting - Padding / Stuffing
characters to a String.
Many a time we will need to format strings by padding Zeros, Blank Spaces or other characters to String.
In C# we can pad characters to a string using
the PadLeft & PadRight methods
PadLeft –
Pads Spaces/characters to the left of the sting.
PadRight – Pads Spaces/characters to the right of the string.
PadRight – Pads Spaces/characters to the right of the string.
There are 2 overridden versions for these
methods.
Syntax
public string PadLeft(int Length) – Pads blank spaces to the Left till the Length is reached.
public string PadLeft(int Length) – Pads blank spaces to the Left till the Length is reached.
public string PadLeft(int Length, char C)
– Pads character C to the Left till the Length is reached.
public string PadRight(int Length) – Pads blank spaces to the Right till the Length is reached.
public string PadRight (int Length, char C)
– Pads character C to the Right till the Length is reached.
Example
string strAmount = "100"
strAmount.PadLeft(5) – " 100"
strAmount.PadLeft(5, '0') – "00100"
strAmount.PadRight(5, '0') – "10000"
strAmount.PadLeft(5) – " 100"
strAmount.PadLeft(5, '0') – "00100"
strAmount.PadRight(5, '0') – "10000"
That’s it we have seen how to Pad Leading / Lagging characters to a String in C#
No comments:
Post a Comment