The String PadRight()
method returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified character.
Example
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
string result;
// returns string of length 15
// padded with space at right
result = str.PadRight(15);
Console.WriteLine("|{0}|", result);
Console.ReadLine();
}
}
}
// Output: |Icecream |
PadRight() Syntax
The syntax of the string PadRight()
method is:
PadRight(int totalWidth, char paddingChar)
Here, PadRight()
is a method of class String
.
PadRight() Parameters
The PadRight()
method takes the following parameters:
- totalWidth - number of characters in the resulting string (number of characters in given string plus additional padding characters)
- paddingChar - padding character
PadRight() Return Value
The PadRight()
method returns:
- new string with right padding
Example 1: C# String PadRight()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
string result;
// returns new string with length 20
// padded with space at right
result = str.PadRight(20);
Console.WriteLine("|{0}|", result);
// returns original string
result = str.PadRight(2);
Console.WriteLine("|{0}|", result);
// returns new string
// identical to given string
result = str.PadRight(8);
Console.WriteLine("|{0}|", result);
Console.ReadLine();
}
}
}
Output
|Icecream | |Icecream| |Icecream|
Here,
str.PadRight(20)
- returns new string with length 20 padded with spaces at rightstr.PadRight(2)
- returns given string as totalWidth is less than length of the given stringstr.PadRight(8)
- returns new string that is identical to the given string as totalWidth is equal to length of the string
Example 2: C# String PadRight() With paddingChar
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
char pad = '^';
string result;
// returns new string with length 20
// padded with '^' at right
result = str.PadRight(20, pad);
Console.WriteLine("|{0}|", result);
// returns given string
result = str.PadRight(2, pad);
Console.WriteLine("|{0}|", result);
// returns new string with length 8
// padded with '^' at right
result = str.PadRight(8, pad);
Console.WriteLine("|{0}|", result);
Console.ReadLine();
}
}
}
Output
|Icecream^^^^^^^^^^^^| |Icecream| |Icecream|