Padding in 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()
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.
-
- string hello = "Hello C# Corner.";
-
- string hello50 = hello.PadLeft(50);
- Console.WriteLine(hello50);
-
- string helloHash = hello.PadLeft(50, '#');
- Console.WriteLine(helloHash);
Listing 1.
The output of Listing 1 looks like Figure 1.
String.PadRight()
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 colon in a string.
-
- string hello = "Hello C# Corner.";
-
- string hello50 = hello.PadRight(50);
- Console.WriteLine(hello50);
-
- string helloHash = hello.PadRight(50, '#');
- Console.WriteLine(helloHash);
Listing 2.
The output of Listing 2 looks like Figure 2.
Figure 2