C# 字符串格式化和填充 [英] C# string formatting and padding

查看:76
本文介绍了C# 字符串格式化和填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来这应该是简单的事情,但我一直没能做对.我看过 http://idunno.org/archive/2004/14/01/122.aspx 供参考.

Seems like this should be something straightforward, but I haven't been able to get it right. I've looked at http://idunno.org/archive/2004/14/01/122.aspx for reference.

示例:我想打印一个双值表,每个双输出具有 3 个小数精度,并占用 10 个空格(左对齐).从概念上讲,我尝试过这样的事情,但它只能用于精确或填充,而不是两者:

Example: I would like to print a table of double values, with each double output having 3 decimal precision, and take up 10 spaces (left aligned). Conceptually, I tried something like this, but it only works with precision OR padding, not both:

foreach(line in lines)
{
    foreach (double val in line)
    {
         Console.Write("{0:0.000,-10}", val);
    }

    Console.WriteLine()
}

更新:我可以在非常简单的场景中使用 padleft/padright,如果我有更复杂的输出,它会变得不是很简洁.有没有类似于sprintf的东西?

Update: I can use padleft/padright in very simple scenarios, if i have more complicated output it becomes not very concise. Is there something similar to sprintf?

推荐答案

尝试

double d = 3.14;
Console.WriteLine("{0,10:0.000}", d);

PS:看看这篇文章作为字符串格式的入门.此外,string.Format 应该允许你做 sprintf 所做的一切——实际上更多......你还想做什么?

P.S: have a look at this article as a primer on string formatting. Also, string.Format should allow you doing everything sprintf does - and actually more... what else are you trying to do?

这篇关于C# 字符串格式化和填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆