一、轉義
C# 中使用類似 {0}, {1:yyyy-MM-dd} 這樣的格式預留位置,如果被格式化字串本身包含 { 或者 } 怎麼辦呢?答案是:用兩個 { 或者 }連寫表示單個。
例如
string str1 = String.Format("{{Hello}}, {0}, Now is {{{1:yyyy-MM-dd HH:mm:ss}}}",
"Jinglecat",
DateTime.Now); // {Hello}, Jinglecat, Now is {2007-07-18 23:06:35}
string str2 = String.Format("{Hello}, {0}, Now is {{1:yyyy-MM-dd HH:mm:ss}}",
"Jinglecat",
DateTime.Now); // --> System.FormatException: 輸入字串的格式不正確。
事實上,很多情況下帶特殊含義的字元都是這樣轉義的:如,
C# 中,當字串常量帶 @ 前置的時候,用兩個 " 連寫表示一個 " (半形雙引號)
string str3 = @"My UserName is ""Jinglecat""."; // My UserName is "Jinglecat".
//string str4 = @"My UserName's "Jinglecat""; // error CS1002: 應輸入 ;
//string str5 = @"My UserName's \"Jinglecat\""; // error CS1002: 應輸入 ;
SQL 字串常量,用兩個 ' 連寫表示一個 ' (半形單引號)
DECLARE @str6 varchar(100)
SET @str6 = 'My UserName is ''Jinglecat''.'
PRINT @str6 -- My UserName is 'Jinglecat'.
Regex中用,兩個 $ 連寫表示一個 $ (dollar)
二、String Formatting in C#
基本內容是:可以在 Console.WriteLine(以及 String.Format,它被 Console.WriteLine 調用)中的格式字串內的括弧中放入非索引數位內容。格式規範的完整形式如下:
{index [, width][:formatstring]}
其中,index 是此格式程式引用的格式字串之後的參數,從零開始計數;width(如果有的話)是要設定格式的欄位的寬度(以空格計)。width 取正數表示結果靠右對齊,取負數則意味著數字在欄位中靠左對齊。(請參閱下面的前兩個樣本。)
formatstring 是可選項,其中包含有關設定類型格式的格式說明。如果對象實現 IFormattable,formatstring 就會傳遞給對象的 Format 方法(在 Beta 2 和後續版本中,該方法的簽名變為 ToString(string, IFormatProvider),但功能不變)。如果對象不實現 IFormattable,就會調用 Object.ToString(),而忽略 formatstring。
另請注意,在 Beta 1 中不區分當前語言的 ToString 在 Beta 2 和後續版本中“將”區分語言。例如,對於用“.”分隔千位,用“,”分隔小數的國家,1,234.56 將會格式化成 1.234,56。如果您需要結果無論在什麼語言下都是一樣的,就請使用 CultureInfo.InvariantCulture 作為語言。
若要擷取有關格式的完整資訊,請查閱“.NET 架構開發人員指南”中的格式概述(英文)。
例如:String.Format("[{0,-10:0##.#0}]", 14)="[014.00 ]";-10表示靠左對齊,總共佔10位,不夠了補Null 字元。
Strings
There really isn’t any formatting within a strong, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call.
| Sample |
Generates |
| String.Format(”->{1,10}<-”, “Hello”); |
-> Hello<- |
| String.Format(”->{1,-10}<-”, “Hello”); |
->Hello <- |
Numbers
Basic number formatting specifiers:
| Specifier |
Type |
Format |
Output (Passed Double 1.42) |
Output (Passed Int -12400) |
| c |
Currency |
{0:c} |
$1.42 |
-$12,400 |
| d |
Decimal (Whole number) |
{0:d} |
System.FormatException |
-12400 |
| e |
Scientific |
{0:e} |
1.420000e+000 |
-1.240000e+004 |
| f |
Fixed point |
{0:f} |
1.42 |
-12400.00 |
| g |
General |
{0:g} |
1.42 |
-12400 |
| n |
Number with commas for thousands |
{0:n} |
1.42 |
-12,400 |
| r |
Round trippable |
{0:r} |
1.42 |
System.FormatException |
| x |
Hexadecimal |
{0:x4} |
System.FormatException |
cf90 |
註:{0:n2}表示千位用,隔開小說點後面兩位
Custom number formatting:
| Specifier |
Type |
Example |
Output (Passed Double 1500.42) |
Note |
| 0 |
Zero placeholder |
{0:00.0000} |
1500.4200 |
Pads with zeroes. |
| # |
Digit placeholder |
{0:(#).##} |
(1500).42 |
|
| . |
Decimal point |
{0:0.0} |
1500.4 |
|
| , |
Thousand separator |
{0:0,0} |
1,500 |
Must be between two zeroes. |
| ,. |
Number scaling |
{0:0,.} |
2 |
Comma adjacent to Period scales by 1000. |
| % |
Percent |
{0:0%} |
150042% |
Multiplies by 100, adds % sign. |
| e |
Exponent placeholder |
{0:00e+0} |
15e+2 |
Many exponent formats available. |
| ; |
Group separator |
see below |
|
|
The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:
註:
如果相應的數字是前置字元為零或尾隨零,“#”字元就會替換為空白值。無論相應數位值如何,“0”字元都會被替換為零字元 — 因此,數字將會被零填補。句號(如果有的話)表示小數分隔字元的位置。
那麼,為什麼要同時使用這些字母,比如“###0.##”? 如果要設定格式的值恰好為零,“#” 圖片字元就被替換為“無”(連零字元也不是)。您可能“總是”希望在小數點的左邊至少有一個“0”,否則,如果值為零,欄位就沒有輸出。換言之,僅包含 “#”字元,一個“0”也沒有的格式常被認為是一個編程錯誤。
例如
string.Format("{0:###.##},14")="14";
string.Format("{0:0##.#0},14")="014.00"
Dates
Note that date formatting is especially dependant on the system’s regional settings; the example strings here are from my local locale.
| Specifier |
Type |
Example (Passed System.DateTime.Now) |
| d |
Short date |
10/12/2002 |
| D |
Long date |
December 10, 2002 |
| t |
Short time |
10:11 PM |
| T |
Long time |
10:11:29 PM |
| f |
Full date & time |
December 10, 2002 10:11 PM |
| F |
Full date & time (long) |
December 10, 2002 10:11:29 PM |
| g |
Default date & time |
10/12/2002 10:11 PM |
| G |
Default date & time (long) |
10/12/2002 10:11:29 PM |
| M |
Month day pattern |
December 10 |
| r |
RFC1123 date string |
Tue, 10 Dec 2002 22:11:29 GMT |
| s |
Sortable date string |
2002-12-10T22:11:29 |
| u |
Universal sortable, local time |
2002-12-10 22:13:50Z |
| U |
Universal sortable, GMT |
December 11, 2002 3:13:50 AM |
| Y |
Year month pattern |
December, 2002 |
The ‘U’ specifier seems broken; that string certainly isn’t sortable.
Custom date formatting:
| Specifier |
Type |
Example |
Example Output |
| dd |
Day |
{0:dd} |
10 |
| ddd |
Day name |
{0:ddd} |
Tue |
| dddd |
Full day name |
{0:dddd} |
Tuesday |
| f, ff, … |
Second fractions |
{0:fff} |
932 |
| gg, … |
Era |
{0:gg} |
A.D. |
| hh |
2 digit hour |
{0:hh} |
10 |
| HH |
2 digit hour, 24hr format |
{0:HH} |
22 |
| mm |
Minute 00-59 |
{0:mm} |
38 |
| MM |
Month 01-12 |
{0:MM} |
12 |
| MMM |
Month abbreviation |
{0:MMM} |
Dec |
| MMMM |
Full month name |
{0:MMMM} |
December |
| ss |
Seconds 00-59 |
{0:ss} |
46 |
| tt |
AM or PM |
{0:tt} |
PM |
| yy |
Year, 2 digits |
{0:yy} |
02 |
| yyyy |
Year |
{0:yyyy} |
2002 |
| zz |
Timezone offset, 2 digits |
{0:zz} |
-05 |
| zzz |
Full timezone offset |
{0:zzz} |
-05:00 |
| : |
Separator |
{0:hh:mm:ss} |
10:43:20 |
| / |
Separator |
{0:dd/MM/yyyy} |
10/12/2002 |
Enumerations
| Specifier |
Type |
| g |
Default (Flag names if available, otherwise decimal) |
| f |
Flags always |
| d |
Integer always |
| x |
Eight digit hex. |
Some Useful Examples
String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, value);
This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.
String.Format(”{0:(###) ###-####}”, 8005551212);
This will output “(800) 555-1212″.