如何在使用动态格式时使用 string.format 用零填充?

How to pad right with zeros using string.format while using dynamic formats?

我有下面的说明性代码。我需要 condition1 的输出右对齐并用 |1234500000| 之类的零填充而不是 |0000012345|而不是固定宽度为 10 的 and 。格式字符串是有条件的,这意味着根据某些条件可以有许多可能的格式字符串之一,而只有一行用于输出。因此,像 PadRight 和 PadLeft 这样的函数不能与值一起使用,除非有一种方法可以在使用它们的同时仍然具有相同的输出行。 (.NET 4.5)

我怎样才能得到|1234500000|同时满足这些要求?

string format;

if (condition1)
format = "|{0:0000000000}|";
else
if (condition2)
format = "|{0}|";
//more conditions here
Int64 value = 12345;
string a = String.Format(format, value);
a.Dump();

内置和可自定义的字符串格式只有这么多。也许您可以为每个条件设置不同的格式化函数,然后稍后再调用它:

Func<Int64, String> formatter;
if (condition1) 
{
    formatter = (number) => number.ToString().PadRight(10, '0');
}
else if (condition2) 
{
    formatter = (number) => number.ToString();
}

Int64 sample = 12345;
string output = string.Format("|{0}|", formatter(sample));
output.Dump();

另一种选择是通过实施 IFormatProviderICustomFormatter 创建您自己的自定义字符串格式提供程序。例如,这是一个可以进行正确填充的草率代码:

public class RightPaddedStringFormatter : IFormatProvider, ICustomFormatter
{
    private int _width;

    public RightPaddedStringFormatter(int width) 
    {
        if (width < 0)
            throw new ArgumentOutOfRangeException("width");

        _width = width;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        // format doubles to 3 decimal places
        return arg.ToString().PadRight(_width, '0');
    }

    public object GetFormat(Type formatType)
    {
        return (formatType == typeof(ICustomFormatter)) ? this : null;
    }
}

然后您可以使用您的条件来选择格式化程序,例如:

IFormatProvider provider;
if (condition1)
{
    provider = new RightPaddedStringFormatter(10);
}
...

Int64 sample = 12345;
string output = string.Format(provider, "|{0}|", sample);
output.Dump();

我从上面的 Possible Duplicate 复制而来,它看起来与 Cory 的回答相似。这允许您 string.Format 并在任一侧填充任何字符,无论它是 0 还是 X,它留给格式化程序。

写成 LinqPad.

void Main()
{
    var val = 12345;
    string.Format(new PaddedStringFormatInfo(), "{0:20:0}", val).Dump();
    string.Format(new PaddedStringFormatInfo(), "{0:-20:0}", val).Dump();
}

public sealed class PaddedStringFormatInfo : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (typeof(ICustomFormatter).Equals(formatType)) return this;

        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg == null) throw new ArgumentNullException("Argument cannot be null");
        if (format == null) return arg.ToString();

        string[] args = format.Split(':');
        if (args.Length == 1) String.Format("{0, " + format + "}", arg);

        int padLength = 0;
        if (!int.TryParse(args[0], out padLength)) throw new ArgumentException("Padding length should be an integer");

        switch (args.Length)
        {
            case 2: // padded format
                if (padLength > 0)  return (arg.ToString()).PadLeft(padLength, args[1][0]);

                return (arg.ToString()).PadRight(padLength * -1, args[1][0]);

            default: // use default string.format
                return string.Format("{0," + format + "}", arg);
        }
    }
}

输出将是:

00000000000000012345
12345000000000000000