http://www.cnblogs.com/linyechengwei/archive/2009/11/17/1604509.html
今天在做項目時,碰到一個很奇怪的問題,我使用string.Format居然報“輸入的字符串格式有誤”的錯誤,我調了很久,還是不對,不明白錯在哪里,后來還是google了一下,原來我在字符串中出現了"{"字符。而"{"字符若出現在string.Format中是必需轉義的,也就是要用兩個"{{"代表一個"{",同時雙下面把我查找到的解決方法的相關文章一同粘貼出來。
一、轉義
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@str6varchar(100)
SET@str6 = 'My UserName is ''Jinglecat''.'
PRINT@str6-- My UserName is 'Jinglecat'.
正則表達式中用,兩個 $ 連寫表示一個 $ (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位,不夠了補空字符。
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″.