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() method has two overloaded forms.
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() method has two overloaded forms.
// 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