.PadRight()
Published Dec 16, 2024
Contribute to Docs
The .PadRight()
method in C# is used to add padding characters to the right of a string to achieve a specified total length. By default, it uses spaces as the padding character, but a custom character can also be specified.
Syntax
string.PadRight(int totalWidth, char paddingChar)
totalWidth
: The desired total length of the string, including padding. If the specified width is less than the string’s length, no padding is added.paddingChar
(Optional): The character to use for padding. Defaults to a space character (' '
).
Note: The
.PadRight()
method does not modify the original string. It generates and returns a new string with padding applied to achieve the specified total width.
Example
Default Padding with Spaces
using System;class Program{static void Main(){string name = "John";string paddedName = name.PadRight(10);Console.WriteLine($"'{paddedName}'");}}
The above code generates the output as follows:
'John '
Custom Padding Character
using System;class NameFormatter{public static void Main(string[] args){string name = "John";string paddedName = name.PadRight(10, '-');Console.WriteLine($"'{paddedName}'");}}
The output of the above code will be:
'John------'
Handling Shorter Total Width
If the specified totalWidth
is less than the length of the string, the original string is returned:
using System;class NamePaddingExample{public static void Main(string[] args){string name = "John";string result = name.PadRight(3);Console.WriteLine($"'{result}'");}}
Here’s what the output of this code will be:
'John'
Codebyte Example
Run the following example to understand how the .PadRight()
method works:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C#
Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.Beginner Friendly23 hours