C# Tutorial C# Advanced C# References

C# String - PadRight() Method



The C# PadRight() method returns a new string that left-aligns the characters of the given string by padding them with spaces or Unicode character on the right, for a specified total length. However, if the parameter totalWidth is specified less than the number of characters in the string, the method returns the reference of the existing instance. If the totalWidth is equal to the number of characters in the string, the method returns a new string identical to the instance.

Note: This method can be overloaded by passing different type of arguments to it.

Syntax

public string PadRight (int totalWidth);
public string PadRight (int totalWidth, char paddingChar);

Parameters

totalWidth Specify the number of characters in the final string equal to the number of characters in the original string plus number of padding characters.
culture Specify a Unicode padding character.

Return Value

Returns the padded version of the string.

Exception

Throws ArgumentOutOfRangeException, if the totalWidth is less than zero.

Example:

In the example below, PadRight() method returns the padded version of the string called MyStr.

using System;

class MyProgram {
  static void Main(string[] args) {
    string MyStr = "Hello World";

    Console.WriteLine(MyStr.PadRight(20));
    Console.WriteLine(MyStr.PadRight(20, '#')); 

    Console.WriteLine();
    Console.WriteLine(MyStr.PadRight(5));
    Console.WriteLine(MyStr.PadRight(5, '#')); 
  }
}

The output of the above code will be:

Hello World         
Hello World#########

Hello World
Hello World

❮ C# String Methods