2009/05/12

String.Format 字串格式化

常要做字串格式,利用 String.Format() 可以快速達到效果,不用為了組字串或特殊格式呈現,東少一個連接字串符號,右少一個引號... 若格式改來改去也很麻煩~ String.Format 可省去很多麻煩,彈性又大~~

String.Format 語法:
{index[,length][:formatString]}
e.g. String.Format("{0:d}", Now)
output: 5/13/2009


以下為字串格式化總覽:

標準數字格式化
(C) Currency:  {0:C}
(D) Decimal: {0:D}
(E) Scientific: {0:E}
(F) Fixed point: {0:F}
(G) General: {0:G}
(N) Number: {0:N}
(P) Percent: {0:P}
(R) Round-trip: {0:R}
(X) Hexadecimal: {0:X}

標準日期/時間格式化
(d) Short date:                  {0:d}
(D) Long date: {0:D}
(t) Short time: {0:t}
(T) Long time: {0:T}
(f) Full date/short time: {0:f}
(F) Full date/long time: {0:F}
(g) General date/short time: {0:g}
(G) General date/long time: {0:G}
(M) Month: {0:M}
(R) RFC1123: {0:R}
(s) Sortable: {0:s}
(u) Universal sortable: {0:u} (invariant)
(U) Universal full date/time: {0:U}
(Y) Year: {0:Y}
0 v.s. #
另外 {0:00.00} 或 {0:##.##} 在利用數字格式化也常使用
用 0 就是補 0,而 # 在末數為 0 時就不顯示

e.g.
{00.00} 01.50; 11.30; 01.11; 123.30; 123.33
{##.##} .4; 1.4; 1; 1.33; 11.3; 123.33

多參數字串:
e.g. String.Format("{0}, Now is {1:d}", "Hello", Now)
output: Hello, Now is 5/13/2009


延伸閱讀:
MSDN - String..::.Format Method (String, Object)
ASP.NET设置数据格式与String.Format使用总结
Easily format string output with String.Format
ASP.NET string.Format 格式參數

沒有留言: