C# String - PadRight() Method



The C# String PadRight() method returns a new string of a specified length, in which the end of the current string padded with space or a specified Unicode character (i.e., the string is left-aligned by padding it with space or the specified character on the right).

Syntax

Following are the syntax of the C# string PadRight() method −

Default Syntax

Returns a new string that left-aligns the characters in the current string by padding them with spaces on the right by the specified length.

public string PadRight (int totalWidth);

Parameterized Syntax

Returns a new string that left-aligns the characters in the current string by padding them with a specified character on the right by the specified length.

public string PadRight (int totalWidth, char paddingChar);

Parameters

This method accepts the following parameters −

  • totalWidth: The number of character in the resulting string, including the original string and any padding characters.
  • paddingChar: It is an optional parameter that represent a padding character.

Return Value

This method returns a new string. That is equivalent to the current string, but left-aligned and padded on the right with spaces or characters.

Example 1: Default Padding with Space

Following is a basic example of the PadRight() method to align the string left by padding with space on the right by a specified length −

    
using System;
class Program {
   static void Main() {
      string original = "tutorialspoint";
      string padded_right = original.PadRight(20);
      Console.WriteLine($"'{padded_right}'");
   }
}

Output

Following is the output −

'tutorialspoint      '

Example 2: Padding with Custom Character

Let's look at another example. Here, we use the PadRight() method to align the string left by padding with specified character on the right −

using System;
class Program {
   static void Main() {
      string original = "Tutorialspoint";
      string padded_right = original.PadRight(20, '-');

      Console.WriteLine($"'{padded_right}'");
   }
}

Output

Following is the output −

'Tutorialspoint------'

Example 3: What if Total Length is Small than String

The below example shows how the PadRight() method works if the total length is smaller than the string. If totalWidth is less than the length of the current string, the method returns a reference to the existing string −

using System;
class Program {
   static void Main() {
      string original = "Tutorialspoint";
      string padded_right = original.PadRight(14, '-');

      Console.WriteLine($"'{padded_right}'");
   }
}

Output

Following is the output −

'Tutorialspoint'
csharp_strings.htm
Advertisements