如何设置一个字符串的多个参数来居中对齐? [英] How can I set a string's multiple argument to align center?
本文介绍了如何设置一个字符串的多个参数来居中对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像下面的字符串,我想每个参数的对准中心,我们有选项左边是(+)和正确的为( - )
basketItemPrice =的String.Format(\\\
\\\
{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的空间,从左至右画,但我想它在是中心对齐中心画
< DIV CLASS =h2_lin>解决方案
不幸的是,这是没有原生的String.Format
。你将不得不垫您的字符串自己:
静态字符串centeredString(字符串s,诠释宽度)
{
如果(s.Length> =宽度)
{
返回小号;
}
INT leftPadding =(宽度 - s.Length)/ 2;
INT rightPadding =宽度 - s.Length - leftPadding;
返回新的字符串('',leftPadding)+ S +新的字符串('',rightPadding);
}
用法示例:
Console.WriteLine(的String.Format(| {0} |,centeredString(你好,10)));
Console.WriteLine(的String.Format(| {0} |,centeredString(世界!,10)));
I have a string like below, and I want each of argument to align center, we have option for left that is(+) and right that is (-)
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));
But I want to align center.
EDIT :- Center align for each text to the space it cover...like first argument takes 5 space and draws from left but i want it to draw in the center that is center align.
解决方案
Unfortunately, this is not supported natively by String.Format
. You will have to pad your string yourself:
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);
}
Usage example:
Console.WriteLine(string.Format("|{0}|", centeredString("Hello", 10)));
Console.WriteLine(string.Format("|{0}|", centeredString("World!", 10)));
这篇关于如何设置一个字符串的多个参数来居中对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文