.PadRight()

itispragativerma6560850080's avatar
Published Dec 16, 2024
Contribute to Docs

The .PadRight() method in C# is used to add padding characters to the right of a string to achieve a specified total length. By default, it uses spaces as the padding character, but a custom character can also be specified.

Syntax

string.PadRight(int totalWidth, char paddingChar)
  • totalWidth: The desired total length of the string, including padding. If the specified width is less than the string’s length, no padding is added.
  • paddingChar(Optional): The character to use for padding. Defaults to a space character (' ').

Note: The .PadRight() method does not modify the original string. It generates and returns a new string with padding applied to achieve the specified total width.

Example

Default Padding with Spaces

using System;
class Program
{
static void Main()
{
string name = "John";
string paddedName = name.PadRight(10);
Console.WriteLine($"'{paddedName}'");
}
}

The above code generates the output as follows:

'John '

Custom Padding Character

using System;
class NameFormatter
{
public static void Main(string[] args)
{
string name = "John";
string paddedName = name.PadRight(10, '-');
Console.WriteLine($"'{paddedName}'");
}
}

The output of the above code will be:

'John------'

Handling Shorter Total Width

If the specified totalWidth is less than the length of the string, the original string is returned:

using System;
class NamePaddingExample
{
public static void Main(string[] args)
{
string name = "John";
string result = name.PadRight(3);
Console.WriteLine($"'{result}'");
}
}

Here’s what the output of this code will be:

'John'

Codebyte Example

Run the following example to understand how the .PadRight() method works:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C# on Codecademy