Padding String in C#
Padding in the string is adding a space or other character at the beginning or end of a string. The String class has String.PadLeft() and String.PadRight() methods to pad strings in left and right sides.
In C#, Strings are immutable. That means the method does not update the existing string but returns a new string.
String.PadLeft() in C#
String.PadLeft() method has two overloaded forms.
Method |
Description |
PadLeft(Int32) |
Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length. |
PadLeft(Int32, Char) |
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. |
Example
The following example replaces all commas with colons in a string.
// Pad left example
string hello = "Hello C# Corner.";
// Make string size 50. All left side will be spaces
string hello50 = hello.PadLeft(50);
Console.WriteLine(hello50);
// Pad left with a character
string helloHash = hello.PadLeft(50, '#');
Console.WriteLine(helloHash);
Listing 1.
The output of Listing 1 looks like Figure 1.
Figure 1.
String.PadRight() in C#
String.PadRight() method has two overloaded forms.
Method |
Description |
PadRight(Int32) |
Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length. |
PadRight(Int32, Char) |
Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length. |
Example
The following example replaces all commas with colons in a string.
// Pad right example
string hello = "Hello C# Corner.";
// Make string size 50. All right side will be spaces
string hello50 = hello.PadRight(50);
Console.WriteLine(hello50);
// Pad right with a character
string helloHash = hello.PadRight(50, '#');
Console.WriteLine(helloHash);
Listing 2.
The output of Listing 2 looks like Figure 2.
Figure 2