C# String PadRight

Summary: in this tutorial, you will learn how to use the C# String PadRight() to pad a specified character on the right side of a string to achieve a desired length.

Introduction to the C# String PadRight method

The String PadRight() method pads a space or a specified character on the right side of the current string to achieve a desired length.

The following PadRight() method pads the current string with spaces on the right for a specified total length:

public string PadRight (
   int totalWidth
);Code language: C# (cs)

In this syntax, the totalWith is the desired length of the resulting string that includes the original string and additional padding spaces.

For example, the following program uses the PadRight() method to display heading with the width of 20:

using static System.Console;

string[] headings = { "Invoice No.", "Description", "Amount" };

foreach (var header in headings)
{
    Write("|");
    Write(header.PadRight(20));
}
Write("|");Code language: C# (cs)

Output:

|Invoice No.         |Description         |Amount              |Code language: plaintext (plaintext)

The PadRight() method has an overload that allows you to pad a string with a specified character on the left to get the resulting string with a specified length:

public string PadRight (
    int totalWidth, 
    char paddingChar
);Code language: C# (cs)

In this syntax, the paddingChar is the character for padding.

For example, the following program uses the PadRight() method to add three dots to a string:

using static System.Console;

var excerpt = "This is a blog's excerpt";
excerpt = excerpt.PadRight(excerpt.Length + 3, '.');

WriteLine(excerpt);
Code language: C# (cs)

Output:

This is a blog's excerpt...Code language: plaintext (plaintext)

Summary

  • Use the C# String PadRight() method to pad a string with a specified character on the right to a desired length.
Was this tutorial helpful ?