C 中的字串內插

2022-01-13 20:17:36 字數 2746 閱讀 1699

$ 特殊字元將字串文字標識為內插字串。 內插字串是可能包含內插表示式的字串文字。 將內插字串解析為結果字串時,帶有內插表示式的項會替換為表示式結果的字串表示形式。 此功能在 c# 6 及該語言的更高版本中可用。

與使用字串復合格式設定功能建立格式化字串相比,字串內插提供的語法更具可讀性,且更加方便。 下面的示例使用了這兩種功能生成同樣的輸出結果:

string name = "

mark";

var date =datetime.now;

//composite formatting:

console.writeline("

hello, ! today is , it's now.

", name, date.dayofweek, date);

//string interpolation:

console.writeline($"

hello, ! today is , it's now.");

//both calls produce the same output that is similar to:

//hello, mark! today is wednesday, it's 19:40 now.

內插字串的結構

若要將字串標識為內插字串,可在該字串前面加上 $ 符號。 字串文字開頭的 $ 和 " 之間不能有任何空格。 如果有空格,會導致編譯時錯誤。

具備內插表示式的項的結構如下所示:

括號中的元素是可選的。 下表說明了每個元素:

interpolatedexpression 生成需要設定格式的結果的表示式。 null 結果的字串表示形式為 string.empty。

alignment 常數表示式,它的值定義內插表示式結果的字串表示形式中的最小字元數。 如果值為正,則字串表示形式為右對齊;如果值為負,則為左對齊。 有關詳細資訊,請參閱對齊元件。

formatstring 受表示式結果型別支援的格式字串。 有關更多資訊,請參閱格式字串元件。

以下示例使用上述可選的格式設定元件:

console.writeline($"

|||"

);const

int fieldwidthrightaligned = 20

;console.writeline($

" - default formatting of the pi number");

console.writeline($

" - display only three decimal digits of the pi number");

//expected output is:

//|left | right|

- default formatting of the pi number

- display only three decimal digits of the pi number

特殊字元

要在內插字串生成的文字中包含大括號 "",請使用兩個大括號,即 "}"。 有關詳細資訊,請參閱轉義大括號。

因為冒號 (":") 在內插表示式項中具有特殊含義,為了在內插表示式中使用條件運算子,請將表示式放在括號內。

以下示例演示如何將大括號含入結果字串中,以及如何在內插表示式中使用條件運算子:

string name = "

horace";

int age = 34

;console.writeline($

"he asked, \"is your name ?\", but didn't wait for a reply :- is year old.");

//expected output is:

//he asked, "is your name horace?", but didn't wait for a reply :- km/s.";

system.globalization.cultureinfo.currentculture = system.globalization.cultureinfo.getcultureinfo("

nl-nl");

string messageincurrentculture =message.tostring();

var specificculture = system.globalization.cultureinfo.getcultureinfo("

en-in");

string messageinspecificculture =message.tostring(specificculture);

string messageininvariantculture =formattablestring.invariant(message);

console.writeline($"

");console.writeline($"

");console.writeline($"

");//expected output is:

//nl-nl the speed of light is 299.792,458 km/s.

//en-in the speed of light is 2,99,792.458 km/s.

//invariant the speed of light is 299,792.458 km/s.

本文**:

C 中內插字串的使用( )

內插字串是c 6.0中引入的新的語法,它允許在字串中插入表示式。相比string.format 它不需要格式字串中的序號與params陣列中的位置對應,可讀性高,便於閱讀。內插字串以 開頭,它可以直接在括號中編寫c 表示式。內插字串內可以繼續插入字串。class program name strin...

建立內插字串

在互動式視窗中,執行以下 選擇 進入焦點模式 按鈕。然後,在互動式視窗中鍵入以下 塊 將替換為自己的名稱 再選擇 執行 c 複製 console.writeline hello,it s a pleasure to meet you var name console.writeline hello,...

C 內插字串中數字保留指定位數

在內插字串中,有時候需要將數字保留特定位數顯示,比較常用的方法是使用下面 var number 10 console.writeline 這是用來測試的數字 可以將數字保留兩位小數進行顯示,如果不足兩位則補0,如果想在小數點前保留特定位數,可以這樣寫 var number 10 console.wr...