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]

  • 相关阅读:
    DS博客作业02--栈和队列
    DS博客作业02--线性表
    c博客06-结构
    c博客作业05--指针
    C博客作业04--数组
    博客作业03-函数
    循环结构
    c博客作业01--分支、顺序结构
    我的第一篇博客
    Macos安装JDK1.8
  • 原文地址:https://www.cnblogs.com/cuihongyu3503319/p/14242287.html
Copyright © 2011-2022 走看看