zoukankan      html  css  js  c++  java
  • C# String 前面不足位数补零的方法

    一:在 C# 中可以对字符串使用 PadLeft 和 PadRight 进行轻松地补位。


    PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度
    PadLeft(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度
    例如:
    1、string aa = "wu";

    string bb = aa.PadLeft(6);//右对齐此实例中的字符,在左边用空格填充以达到指定的总长度.
    string cc = aa.PadLeft(6, '0');//右对齐此实例中的字符,在左边用指定的 Unicode 字符填充以达到指定的总长度。
    2、Pznm =(snode.InnerText).ToString().PadLeft(10,'0');
    字符串固定为10位,不足10位左边补零。

    二:String.Format("{0:D5}",16);
    or
     int i=16;
     i.ToString("D5");
    Result: 00016
     
    5代表位数

    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 长度
    PadRight(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度
    示例:
    h = h.PadLeft(2, '0');
    注意第二个参数为 char 类型,所以用单引号,也可以用 Convert.ToChar(string value) 把字符串转换成 char 类型。如果字符串长度大于 1,则使用 str.ToCharArray()[index]

  • 相关阅读:
    找水王
    统计txt文档中的单词个数
    返回一个数组中最大子数组的和
    寻找最长字符串
    第二阶段冲刺第九天
    第二阶段冲刺第八天
    第二阶段冲刺第七天
    第二阶段冲刺第六天
    构建之法阅读笔记06
    小目标
  • 原文地址:https://www.cnblogs.com/shiyh/p/10494240.html
Copyright © 2011-2022 走看看