如何设置字符串的多个参数以对齐中心?
我有一个像下面的字符串,我希望每个参数对齐中心,我们有左边的选项是(+)和右边是( – )
basketItemPrice = string.Format("\n\n{0, -5}{1, -14:0.00}{2, -18:0.00}{3,-14:0.00}{4,6}{5,-12:0.00}", item.Quantity, item.OrderItemPrice, item.MiscellaniousCharges, item.DiscountAmountTotal, "=", item.UpdateItemAmount(Program.currOrder.OrderType));
但我想调整中心。
编辑: – 将每个文本的中心对齐到它所覆盖的空间…就像第一个参数需要5个空格并从左边绘制但我希望它在中心对齐的中心绘制。
不幸的是, String.Format
本身不支持这一点。 你必须自己填充你的字符串:
static string centeredString(string s, int width) { if (s.Length >= width) { return s; } int leftPadding = (width - s.Length) / 2; int rightPadding = width - s.Length - leftPadding; return new string(' ', leftPadding) + s + new string(' ', rightPadding); }
用法示例:
Console.WriteLine(string.Format("|{0}|", centeredString("Hello", 10))); Console.WriteLine(string.Format("|{0}|", centeredString("World!", 10)));
我试图制作一个仍然保留IFormattable
支持的扩展方法。 它使用嵌套类来记住原始值和所需宽度。 然后,当提供格式字符串时,如果可能,使用它。
它看起来像这样:
public static class MyExtensions { public static IFormattable Center(this T self, int width) { return new CenterHelper (self, width); } class CenterHelper : IFormattable { readonly T value; readonly int width; internal CenterHelper(T value, int width) { this.value = value; this.width = width; } public string ToString(string format, IFormatProvider formatProvider) { string basicString; var formattable = value as IFormattable; if (formattable != null) basicString = formattable.ToString(format, formatProvider) ?? ""; else if (value != null) basicString = value.ToString() ?? ""; else basicString = ""; int numberOfMissingSpaces = width - basicString.Length; if (numberOfMissingSpaces <= 0) return basicString; return basicString.PadLeft(width - numberOfMissingSpaces / 2).PadRight(width); } public override string ToString() { return ToString(null, null); } } }
注意:在需要附加奇数个空格字符的情况下,您没有指出是否要将一个“额外”空格字符放在左侧或右侧。
此测试似乎表明它有效:
double theObject = Math.PI; string test = string.Format("Now '{0:F4}' is used.", theObject.Center(10));
当然,格式字符串F4
带有double
意味着“小数点后四舍五入小数”。
我不确定你的问题,但我希望这可以帮助你:
public static class StringHelper { public static string Center(this String value, int width) { var padding = (width + value.Length) / 2; return value.PadLeft(padding, '#'); } }
如果要绘制位图,请使用Graphics.DrawString(..)方法,并将字符串对齐设置为居中。
这里有很多例子:
http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.linealignment.aspx