跳到主要内容

C# String PadRight() 字符串右填充方法

String 类的 PadRight() 方法返回一个指定长度的新字符串,其中当前字符串的末尾用空格或指定字符填充。

示例

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Icecream";
string result;

// 返回长度为 15 的字符串
// 右侧用空格填充
result = str.PadRight(15);
Console.WriteLine("|{0}|", result);

Console.ReadLine();
}
}
}

// 输出:|Icecream |

PadRight() 方法语法

字符串 PadRight() 方法的语法是:

PadRight(int totalWidth, char paddingChar)

这里,PadRight()String 类的一个方法。

PadRight() 方法参数

PadRight() 方法接受以下参数:

  • totalWidth - 结果字符串中的字符数量(给定字符串中的字符数量加上额外的填充字符)
  • paddingChar - 填充字符

PadRight() 方法返回值

PadRight() 方法返回:

  • 带有右侧填充的新字符串

示例 1:C# 字符串 PadRight()

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Icecream";
string result;

// 返回长度为 20 的新字符串
// 右侧用空格填充
result = str.PadRight(20);
Console.WriteLine("|{0}|", result);

// 返回原始字符串
result = str.PadRight(2);
Console.WriteLine("|{0}|", result);

// 返回与给定字符串相同的新字符串
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# 字符串 PadRight() 使用 paddingChar

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Icecream";
char pad = '^';
string result;

// 返回长度为 20 的新字符串
// 右侧用 '^' 填充
result = str.PadRight(20, pad);
Console.WriteLine("|{0}|", result);

// 返回给定字符串
result = str.PadRight(2, pad);
Console.WriteLine("|{0}|", result);

// 返回长度为 8 的新字符串
// 右侧用 '^' 填充
result = str.PadRight(8, pad);
Console.WriteLine("|{0}|", result);

Console.ReadLine();
}
}
}

输出

|Icecream^^^^^^^^^^^^|
|Icecream|
|Icecream|