String PadRight()
方法返回一个指定长度的新字符串,该字符串的末尾用空格或指定的字符进行填充。
示例
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() 语法
字符串 PadRight()
方法的语法是:
PadRight(int totalWidth, char paddingChar)
这里,PadRight()
是 String
类的一个方法。
PadRight() 参数
PadRight()
方法接受以下参数:
- totalWidth - 结果字符串中的字符数(给定字符串中的字符数加上额外的填充字符)
- paddingChar - 填充字符
PadRight() 返回值
PadRight()
方法返回:
- 带右填充的新字符串
示例 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();
}
}
}
输出
|Icecream | |Icecream| |Icecream|
这里,
str.PadRight(20)
- 返回一个长度为 **20** 的新字符串,右侧用空格填充str.PadRight(2)
- 返回给定字符串,因为 totalWidth 小于给定字符串的长度str.PadRight(8)
- 返回一个与给定字符串完全相同的新字符串,因为 totalWidth 等于字符串的长度
示例 2:C# String PadRight() 带 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();
}
}
}
输出
|Icecream^^^^^^^^^^^^| |Icecream| |Icecream|