跳到主要内容

C# String PadLeft() 字符串左填充方法

String的PadLeft()方法返回一个新的字符串,该字符串具有指定的长度,其中当前字符串的开头填充了空格或指定的字符。

示例

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

string str = "冰淇淋";

// 返回长度为9的字符串
// 左侧填充一个空格
string result = str.PadLeft(9);
Console.WriteLine(result);

Console.ReadLine();
}
}
}

// 输出: 冰淇淋

PadLeft() 语法

字符串PadLeft()方法的语法如下:

PadLeft(int totalWidth, char paddingChar)

这里,PadLeft()String类的方法。

PadLeft() 参数

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

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

PadLeft() 返回值

PadLeft()方法返回:

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

示例1:C# String PadLeft()

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

string str = "冰淇淋";
string result;

// 返回长度为20的新字符串
// 左侧填充空格
result = str.PadLeft(20);
Console.WriteLine("结果: " + result);

// 返回原始字符串
result = str.PadLeft(2);
Console.WriteLine("结果: " + result);

// 返回新字符串
// 与给定字符串相同
result = str.PadLeft(8);
Console.WriteLine("结果: " + result);

Console.ReadLine();
}
}
}

输出

结果:          	冰淇淋
结果: 冰淇淋
结果: 冰淇淋

在这里,

  • str.PadRight(20) - 返回长度为20的新字符串,左侧填充了空格
  • str.PadRight(2) - 返回给定字符串,因为totalWidth小于给定字符串的长度
  • str.PadRight(8) - 返回与给定字符串相同的新字符串,因为totalWidth等于字符串的长度

示例2:C# String PadLeft() 使用填充字符

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

string str = "冰淇淋";
char pad = '^';
string result;

// 返回长度为9的字符串
// 左侧填充'^'
result = str.PadLeft(9, pad);
Console.WriteLine("结果: " + result);

// 返回原始字符串
result = str.PadLeft(2, pad);
Console.WriteLine("结果: " + result);

// 返回长度为20的字符串
// 左侧填充'^'
result = str.PadLeft(20, pad);
Console.WriteLine("结果: " + result);

Console.ReadLine();
}
}
}

输出

结果: ^冰淇淋
结果: 冰淇淋
结果: ^^^^^^^^^^^^冰淇淋