天天看點

string.Format出現異常"輸入的字元串格式有誤"的解決方法

今天在做項目時,碰到一個很奇怪的問題,我使用string.Format居然報“輸入的字元串格式有誤”的錯誤,我調了很久,還是不對,不明白錯在哪裡,後來還是google了一下,原來我在字元串中出現了"{"字元。而"{"字元若出現在string.Format中是必需轉義的,也就是要用兩個"{{"代表一個"{",同時雙下面把我查找到的解決方法的相關文章一同粘貼出來。

一、轉義

例如 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: 輸入字元串的格式不正确。

SQL 字元串常量,用兩個 ' 連寫表示一個 ' (半角單引号) DECLARE @str6 varchar(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 作為語言。

例如:String.Format("[{0,-10:0##.#0}]", 14)="[014.00    ]";-10表示左對齊,總共占10位,不夠了補空字元。

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 <-

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

f

Fixed point

{0:f}

g

General

{0:g}

n

Number with commas for thousands

{0:n}

-12,400

r

Round trippable

{0:r}

x

Hexadecimal

{0:x4}

cf90

注:{0:n2}表示千位用,隔開小說點後面兩位

Custom number formatting:

Example

Output (Passed Double 1500.42)

Note

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.

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"

Note that date formatting is especially dependant on the system’s regional settings; the example strings here are from my local locale.

Example (Passed System.DateTime.Now)

Short date

10/12/2002

D

Long date

December 10, 2002

t

Short time

10:11 PM

T

Long time

10:11:29 PM

Full date & time

December 10, 2002 10:11 PM

F

Full date & time (long)

December 10, 2002 10:11:29 PM

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

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:

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}

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}

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

/

{0:dd/MM/yyyy}

Default (Flag names if available, otherwise decimal)

Flags always

Integer always

Eight digit hex.

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″.

本文轉自左正部落格園部落格,原文連結:http://www.cnblogs.com/soundcode/archive/2012/12/05/2802641.html,如需轉載請自行聯系原作者