将下一个参数作为 String.Format 中的字段宽度

发布于 2024-08-22 11:49:15 字数 248 浏览 9 评论 0原文

在 C# 中,我想为某些字符串使用一个宽度,但直到运行时我才知道该宽度。我正在做这样的事情:

string.Format("{0, " + digits + "}", value)  // prints 123 as "  123"

是否有一个字符串格式化指令可以让我指定它,而无需像这样将我自己的格式字符串粉碎在一起?

我在 MSDN 上浏览了一段时间,我觉得我错过了关于格式字符串之类的一整章。

In C#, I have a width I want to use for some strings, but I won't know that width until runtime. I'm doing something like this:

string.Format("{0, " + digits + "}", value)  // prints 123 as "  123"

Is there a string formatting directive that lets me specify this without smashing my own format string together like this?

I looked around on MSDN for a little while and I feel like I'm missing a whole chapter on format strings or something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

决绝 2024-08-29 11:49:15

看看PadLeft

s = "123".PadLeft(5);  // Defaults to spaces
s = "123".PadLeft(5, '.');  // Pads with dots

Take a look at PadLeft:

s = "123".PadLeft(5);  // Defaults to spaces
s = "123".PadLeft(5, '.');  // Pads with dots
小…楫夜泊 2024-08-29 11:49:15

你可以做类似

string test = valueString.PadLeft(10,' ');

甚至更愚蠢的事情

string spaces = String.Concat(Enumerable.Repeat(" ", digits).ToArray());

you can do something like

string test = valueString.PadLeft(10,' ');

or even sillier

string spaces = String.Concat(Enumerable.Repeat(" ", digits).ToArray());
私野 2024-08-29 11:49:15

其他人提到的功能可以使用,但此 MSDN 页面有一个更通用的解决方案来处理运行时更改的格式:

复合格式

他们给出的示例与您的示例非常相似。

编辑:我认为您正在尝试解决在运行时编写格式字符串的一般情况。例如,如果没有内置的 PadLeft(),您可以这样做:

    int myInt = 123;
    int nColumnWidth = 10;

    string fmt = string.Format("Price = |{{0,{0}}}|", nColumnWidth);

    // now fmt = "Price = |{0,5}|"

    string s = string.Format(fmt, myInt);

您甚至可以在一行中完成所有这些操作,但它很难看:

    string s = string.Format(
            string.Format("Price = |{{0,{0}}}|", nColumnWidth),
            myInt);

The functions mentioned by others will work, but this MSDN page has a more general solution to formatting that changes at runtime:

Composite Formatting

They give examples much like yours.

Edit: I thought you were trying to solve the general case of composing a format string at runtime. For example, if there were no built in PadLeft(), you could do this:

    int myInt = 123;
    int nColumnWidth = 10;

    string fmt = string.Format("Price = |{{0,{0}}}|", nColumnWidth);

    // now fmt = "Price = |{0,5}|"

    string s = string.Format(fmt, myInt);

You can even do all that in one line, but it's ugly:

    string s = string.Format(
            string.Format("Price = |{{0,{0}}}|", nColumnWidth),
            myInt);
回忆凄美了谁 2024-08-29 11:49:15

也许这将有助于您对格式的研究:

格式类型

复合格式

但是,我认为您不会比这要好得多,因为对齐参数必须是格式字符串的一部分,并且似乎不由属性表示。

Perhaps this will help with your research on formatting:

Formatting Types

Composite Formatting

However, I don't think you're going to do much better than this, as the alignment parameter must be part of the format string and does not seem to be represented by a property.

旧瑾黎汐 2024-08-29 11:49:15

可能有点过头了,但只是为了说明一种封装格式规范并使用接受 IFormatProviderString.Format 重载的方法。

class Program
{
    public static void Main(string[] args)
    {
        int digits = 7;
        var format = new PaddedNumberFormatInfo(digits);
        Console.WriteLine(String.Format(format, "{0}", 123));
    }
}
class PaddedNumberFormatInfo : IFormatProvider, ICustomFormatter
{
    public PaddedNumberFormatInfo(int digits)
    {
        this.DigitsCount = digits;
    }

    public int DigitsCount { get; set; }

    // IFormatProvider Members
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;

        return null;
    }
    // ICustomFormatter Members
    public string Format(string format, object arg, IFormatProvider provider)
    {
        return String.Format(
            String.Concat("{0, ", this.DigitsCount, "}"), arg);
    }
}

Probably overkill but just to illustrate a way to encapsulate the format specification and use an overload of String.Format that accepts an IFormatProvider.

class Program
{
    public static void Main(string[] args)
    {
        int digits = 7;
        var format = new PaddedNumberFormatInfo(digits);
        Console.WriteLine(String.Format(format, "{0}", 123));
    }
}
class PaddedNumberFormatInfo : IFormatProvider, ICustomFormatter
{
    public PaddedNumberFormatInfo(int digits)
    {
        this.DigitsCount = digits;
    }

    public int DigitsCount { get; set; }

    // IFormatProvider Members
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;

        return null;
    }
    // ICustomFormatter Members
    public string Format(string format, object arg, IFormatProvider provider)
    {
        return String.Format(
            String.Concat("{0, ", this.DigitsCount, "}"), arg);
    }
}
情归归情 2024-08-29 11:49:15

我发布了一篇 CodeProject 文章,可能正是您想要的。

请参阅:AC# 间接方式宽度和样式格式化。

基本上,它是一种方法 FormatEx,其作用类似于 String.Format,只不过它允许间接对齐和 formatString 说明符。

FormatEx("{0,{1}:{2}}", value, width, formatString);

意味着使用 varArgs 2 指定的格式化字符串代码,在 varArgs 1 指定的字段宽度中格式化 varArgs 0 的值。

编辑:在内部,它执行许多其他人在其答案中建议的操作。我刚刚完成了用于对齐和 formatString 的最终值的解析和确定。我还添加了“中心对齐”修饰符。

-杰西

I posted a CodeProject article that may be what you want.

See: A C# way for indirect width and style formatting.

Basically it is a method, FormatEx, that acts like String.Format, except it allows for indirect alignment and formatString specifiers.

FormatEx("{0,{1}:{2}}", value, width, formatString);

Means format the value of varArgs 0, in a field width specified by varArgs 1, using a formattingString code specified by varArgs 2.

Edit: Internally, it does what many others have suggested in their answers. I've just wrapped the parsing and determination of the final values to use for alignment and formatString. I also added a "center alignment" modifier.

-Jesse

甜宝宝 2024-08-29 11:49:15

String 有一个构造函数,用于创建一个字符串,其中给定字符重复 n 次。

https://msdn.microsoft.com/en-我们/库/xsa4321w(v=vs.110).aspx

// prints 123 as "  123"
string.Format(new string(' ', digits) + "{0}", value)

String has a constructor that creates a string with a given character repeated n times.

https://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx

// prints 123 as "  123"
string.Format(new string(' ', digits) + "{0}", value)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文