C# String PadLeft()

String 的 PadLeft() 方法会返回一个新的、指定长度的字符串,该字符串的开头会用空格或指定的字符进行填充。

示例

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
     
// returns string with length 9 // padded with one space at left string result = str.PadLeft(9);
Console.WriteLine(result); Console.ReadLine(); } } } // Output: Icecream

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 = "Icecream";
      string result;
     
// returns new string with length 20 // padded with space at left result = str.PadLeft(20);
Console.WriteLine("Result: " + result);
// returns original string result = str.PadLeft(2);
Console.WriteLine("Result: " + result);
// returns new string // identical to given string result = str.PadLeft(8);
Console.WriteLine("Result: " + result); Console.ReadLine(); } } }

输出

Result:         	Icecream
Result: Icecream
Result: Icecream

这里,

  • 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 = "Icecream";
      char pad = '^';
      string result;
     
// returns string with length 9 // padded with '^' at left result = str.PadLeft(9, pad);
Console.WriteLine("Result: " + result);
// returns original string result = str.PadLeft(2, pad);
Console.WriteLine("Result: " + result);
// returns string with length 20 // padded with '^' at left result = str.PadLeft(20, pad);
Console.WriteLine("Result: " + result); Console.ReadLine(); } } }

输出

Result: ^Icecream
Result: Icecream
Result: ^^^^^^^^^^^^Icecream
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战