如果你熟悉Microsoft Foundation Classes(MFC)的CString,Windows Template Library(WTL)的CString或者Standard Template Library(STL)的字符串类,那么你对String.Format方法肯定很熟悉。在C#中也经常使用这个方法来格式化字符串,比如下面这样:
int
x
=
16
;
decimal y = 3.57m ;
string h = String.Format( " item {0} sells at {1:C} " , x, y );
Console.WriteLine(h);
decimal y = 3.57m ;
string h = String.Format( " item {0} sells at {1:C} " , x, y );
Console.WriteLine(h);
在我的机器上,可以得到下面的输出:
item 16 sells at ¥3.57
也许你的机器上的输出和这个不太一样。这是正常的,本文稍后就会解释这个问题。
在我们日常使用中,更多的是使用Console.WriteLine方法来输出一个字符串。其实String.Format和Console.WriteLine有很多共同点。两个方法都有很多重载的格式并且采用无固定参数的对象数组作为最后一个参数。下面的两个语句会产生同样的输出。
Console.WriteLine(
"
Hello {0} {1} {2} {3} {4} {5} {6} {7} {8}
"
,
123
,
45.67
,
true
,
'
Q
'
,
4
,
5
,
6
,
7
,
'
8
'
);
string u = String.Format( " Hello {0} {1} {2} {3} {4} {5} {6} {7} {8} " , 123 , 45.67 , true , ' Q ' , 4 , 5 , 6 , 7 , ' 8 ' );
Console.WriteLine(u);
string u = String.Format( " Hello {0} {1} {2} {3} {4} {5} {6} {7} {8} " , 123 , 45.67 , true , ' Q ' , 4 , 5 , 6 , 7 , ' 8 ' );
Console.WriteLine(u);
输出如下:
Hello 123 45.67 True Q 4 5 6 7 8
Hello 123 45.67 True Q 4 5 6 7 8
Hello 123 45.67 True Q 4 5 6 7 8
2 字符串格式
String.Format和WriteLine都遵守同样的格式化规则。格式化的格式如下:"{ N [, M ][: formatString ]}", arg1, ... argN,在这个格式中:
1) N是从0开始的整数,表示要格式化的参数的个数
2) M是一个可选的整数,表示格式化后的参数所占的宽度,如果M是负数,那么格式化后的值就是左对齐的,如果M是正数,那么格式化后的值是右对齐的
3) formatString是另外一个可选的参数,表示格式代码
argN表示要格式化的表达式,和N是对应的。
如果argN是空值,那么就用一个空字符串来代替。如果没有formatString,那么就用参数N对应的ToString方法来格式化。下面的语句会产生同样的输出:
public
class
TestConsoleApp
{
public static void Main( string [] args)
{
Console.WriteLine( 123 );
Console.WriteLine( " {0} " , 123 );
Console.WriteLine( " {0:D3} " , 123 );
}
}
{
public static void Main( string [] args)
{
Console.WriteLine( 123 );
Console.WriteLine( " {0} " , 123 );
Console.WriteLine( " {0:D3} " , 123 );
}
}
输出是:
123
123
123
123
123
也可以通过String.Format得到同样的输出。
string
s
=
string
.Format(
"
123
"
);
string t = string .Format( " {0} " , 123 );
string u = string .Format( " {0:D3} " , 123 );
Console.WriteLine(s);
Console.WriteLine(t);
Console.WriteLine(u);
string t = string .Format( " {0} " , 123 );
string u = string .Format( " {0:D3} " , 123 );
Console.WriteLine(s);
Console.WriteLine(t);
Console.WriteLine(u);
因此有如下结论:
(,M)决定了格式化字符串的宽度和对齐方向
(:formatString)决定了如何格式化数据,比如用货币符号,科学计数法或者16进制。就像下面这样:
Console.WriteLine(
"
{0,5} {1,5}
"
,
123
,
456
);
//
右对齐
Console.WriteLine( " {0,-5} {1,-5} " , 123 , 456 ); // 左对齐
Console.WriteLine( " {0,-5} {1,-5} " , 123 , 456 ); // 左对齐
输出是
123
456
123 456
123 456
也可以合并这些表达式,先放一个逗号,再放一个冒号。就像这样:
Console.WriteLine(
"
{0,-10:D6} {1,-10:D6}
"
,
123
,
456
);
输出是:

我们可以用这种格式化特性来对齐我们的输出。
Console.WriteLine(