C# String PadRight() Method

https:/‮w/‬ww.theitroad.com

The PadRight() method in C# is used to pad a string with a specified character or set of characters on the right side, so that the resulting string has a specified total length. If the length of the original string is greater than or equal to the specified total length, the method returns the original string without any padding.

The syntax of the PadRight() method is as follows:

string.PadRight(totalWidth);

or

string.PadRight(totalWidth, paddingChar);

Here, totalWidth is the total length of the resulting string, including the original string and any padding characters, and paddingChar is the character to use for padding. If paddingChar is not specified, the method uses the space character (' ') for padding.

For example, to pad a string with spaces on the right side so that the resulting string has a total length of 10 characters, you can use the following code:

string text = "Hello";
string paddedText = text.PadRight(10);
Console.WriteLine(paddedText);  // Output: "Hello     "

In this example, the PadRight() method is used to pad the string "Hello" with spaces on the right side so that the resulting string has a total length of 10 characters. The resulting string "Hello " is then assigned to the paddedText variable and printed to the console using the WriteLine() method.

You can also use the PadRight() method to pad a string with a specified character on the right side. For example, to pad a string with zeros on the right side so that the resulting string has a total length of 8 characters, you can use the following code:

string number = "123";
string paddedNumber = number.PadRight(8, '0');
Console.WriteLine(paddedNumber);  // Output: "12300000"

In this example, the PadRight() method is used to pad the string "123" with zeros on the right side so that the resulting string has a total length of 8 characters. The resulting string "12300000" is then assigned to the paddedNumber variable and printed to the console.