C# | Right padding a string with spaces

In this tutorial, we will learn how to right pad a string with spaces in C#? By IncludeHelp Last updated : April 09, 2023

How to right pad a string with spaces in C#?

The string.PadRight() method is used to pad right a string with spaces.

Syntax

string string.PadRight(int totalWidth);

Here, totalWidth is the total number of characters of the string, if it is more than the length of the string, string will be padded with spaces, method returns the space padded string.

C# program to pad right a string with spaces

using System;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      string str = "Hello world";

      Console.WriteLine("Demonstration of PadRight method");
      Console.WriteLine(str.PadRight(str.Length + 1) + "##########");
      Console.WriteLine(str.PadRight(str.Length + 2) + "##########");
      Console.WriteLine(str.PadRight(str.Length + 3) + "##########");
      Console.WriteLine(str.PadRight(str.Length + 4) + "##########");
      Console.WriteLine(str.PadRight(str.Length + 5) + "##########");

      Console.WriteLine();
    }
  }
}

Output

Demonstration of PadRight method
Hello world ##########
Hello world  ##########
Hello world   ##########
Hello world    ##########
Hello world     ##########



All C#.Net Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.