首页 > 解决方案 > 填充未应用于字符串

问题描述

嗨,我只是想在一个字符串数字中添加一个零,例如,一家公司在系统中有一些旧条码,打印时只有 12 个字符,他们的新条码是 13,我只需要添加一个额外的零当它的长度为 12 时。

using System;

public class Program
{
    public static void Main()
    {
         string BarCode="000001661705"; 
         char pad = '0';
         if(BarCode.Length==12)
         {
            BarCode = BarCode.PadLeft(1, pad);       
         }
        Console.WriteLine("Length of barcode" + BarCode.Length);
        Console.WriteLine("Barcode=" + BarCode);        
    }
}

这是.net fillddle,您将看到字符数仍然是12,而应该是13,并在其上添加了零。

https://dotnetfiddle.net/VsvPIl

标签: c#string

解决方案


只需将其添加为字符串?

using System;

public class Program
{
    public static void Main()
    {
        string BarCode="000001661705";

             char pad = '0';
            if(BarCode.Length==12)
            {
                BarCode = pad + BarCode;


            }
        Console.WriteLine("Length of barcode" + BarCode.Length);
        Console.WriteLine("Barcode=" + BarCode);

    }
}

推荐阅读