本文主要介绍字符串补齐方法PadLeft和PadRight,将指定的单个字符把字符串补齐到指定长度。

1、字符串使用 PadLeft 和 PadRight 进行轻松地补位

1)PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度

2)PadRight(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度

2、PadLeft和PadRight的使用示例

string str = "100";
str.PadLeft(5,'0')

输出:00100

str.PadRight(5, '0')

输出:10000

3、实现进行字符串两边补齐方法

1)实现方法

public string PadBoth(string source, int length)
{
int spaces = length - source.Length;
int padLeft = spaces/2 + source.Length;
return source.PadLeft(padLeft).PadRight(length);
}

2)通过扩展方法调用

namespace System
{
public static class StringExtensions
{
public static string PadBoth(this string str, int length)
{
int spaces = length - str.Length;
int padLeft = spaces / 2 + str.Length;
return str.PadLeft(padLeft).PadRight(length);
}
}
}



推荐文档

相关文档

大家感兴趣的内容

随机列表