C# `PadRight()` Method: Efficient String Padding for Formatting

Learn how to use C#'s `PadRight()` method to add padding to strings, ensuring consistent string lengths. This tutorial explains its functionality, demonstrates different padding characters, and highlights its applications in formatting text output and aligning data within fixed-width fields.



Using C# `PadRight()` for String Padding

Understanding `PadRight()`

The C# `PadRight()` method creates a new string by padding the original string with spaces on the right-hand side until it reaches a specified total length. This is useful for formatting strings, ensuring they all have a consistent length, for example, when aligning text in output or working with fixed-width fields.

`PadRight()` Method Signatures

The `PadRight()` method has two versions:

  • public string PadRight(int totalWidth);: Pads with spaces to reach the specified total width.
  • public string PadRight(int totalWidth, char paddingChar);: Pads using the given character to reach the specified total width.

Example: Padding a String with Spaces

This example shows how to pad a string with spaces using the `PadRight()` method. The string "Hello C#" is padded with spaces on the right to a total length of 15 characters. The extra string "JavaTpoint" is added after to demonstrate the padding.

C# Code

using System;

public class PadRightExample {
    public static void Main(string[] args) {
        string str = "Hello C#";
        string paddedStr = str.PadRight(15);
        Console.WriteLine($"{paddedStr}JavaTpoint"); 
    }
}

Conclusion

The `PadRight()` method is a simple yet effective way to format strings in C#, ensuring consistent lengths for improved readability and easier manipulation. Remember that `PadRight()` returns a *new* string; the original string remains unchanged.