int i=10;
方法1:Console.WriteLine(i.ToString("D5"));
方法2:Console.WriteLine(i.ToString().PadLeft(5,'0'));//推荐
方法3:Console.WriteLine(i.ToString("00000"));
在 C# 中可以对字符串使用 PadLeft 和 PadRight 进行轻松地补位。
PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度PadLeft(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度
示例:
h = h.PadLeft(2, '0');
注意第二个参数为 char 类型,所以用单引号,也可以用 Convert.ToChar(string value) 把字符串转换成 char 类型。如果字符串长度大于 1,则使用 str.ToCharArray()[index]。
本文深入探讨了C#中使用PadLeft和PadRight方法进行字符串补位的操作,提供了实例演示及注意事项。通过具体代码示例,详细解释了如何在字符串左侧或右侧填充字符以达到指定长度。
1487

被折叠的 条评论
为什么被折叠?



