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]

  • 相关阅读:
    计算机组成原理
    数据结构和算法: 字符串匹配(一) BF/RK
    数据结构和算法: 动态规划-台阶问题
    数据结构和算法: 散列表
    数据结构和算法: 归并排序/快速排序
    数据结构与算法: 冒泡/插入/选择排序
    过渡内容
    Redis 和缓存技术
    2019字节跳动面试时手撕代码题
    Mysql锁机制
  • 原文地址:https://www.cnblogs.com/shiyh/p/10494240.html
Copyright © 2011-2022 走看看