用 0 填充字符串——格式化样式?

Padding string with 0's -- formatting style?

好的,所以我需要用一定数量的 0 填充字符串值,具体取决于字符串的长度是否为 6 个字符。但结果值不能超过6个字符。

例如:

不幸的是,我现在设置的内容不起作用。它只是将输入的字符串值更改为 D6。 (注意:NMFCItemNum 的值可以为空——在这种情况下,不需要做任何事情)。

我发现 D# 在值前给出了适当数量的 0,但设置错误。

            string NMFCItemNum = GetValue(curCategory, (int)CategoryCols.NMFCItemNum);
            if (NMFCItemNum != "")
            {
                //Save the value of NMFCItemNum as is
                if (NMFCItemNum.Length == 6)
                {
                    cmd.Parameters.Add(new SqlParameter("@NMFCItemNumber", GetValue(curCategory, (int)CategoryCols.NMFCItemNum)));
                }
                else
                {
                    if (NMFCItemNum.Length < 6)
                    {
                        //prefix with 0's then save to database
                        cmd.Parameters.Add(new SqlParameter("@NMFCItemNumber", String.Format("D6",NMFCItemNum)));
                    }
                }
            }
String.Format("D6",NMFCItemNum)

有 "D6" 作为一个简单的字符串。格式化字符串将 "D6" 解释为 "D6"。您需要使用 占位符 :

String.Format("{0:D6}", NMFCItemNum);

说“取第一个参数,将其填入 {0} 位置,并使用 "D6" 格式。

您可以使用string.PadLeft(Total Width, character)方法

NMFCItemNum.PadLeft(6, '0');

是这样的吗?

string str = "1234"
Console.WriteLine(str.PadLeft(8, '0'));  
//00001234