[英]How to escape {0} from Console.Write()
考慮以下輸出
'{0}' is replaced to 'Hello'
要在文本上方打印,我可以這樣寫
Console.Write("'{0}' is replaced to '{1}'", "{0}", "Hello");
但是在這里我想使用單個參數傳遞給該字符串
Console.Write("'{0}' is replaced to '{0}'", "Hello");
^to escape somehow this
我想先轉義“ {0}”。 我試過了
Console.Write("'\\{0}' is replaced to '{0}'", "Hello");
輸出量
'\Hello' is replaced to 'Hello'
有什么方法可以打印“ {0}”,而不是用該字符串的第一個參數(即Console.Write(...)的第二個參數)替換。
對於使用字符串參數的string.Format
和方法,即Console.Write()
和Console.WriteLine()
或String Interpolation ,請使用雙括號
即
使用{{ blah }}
對文字{ blah }
進行編碼。
要么
使用{{0}}
來編碼文字{0}
。
使用I need braces {{ for some reason
編碼I need braces { for some reason
如何在結果字符串中包含文字括號(“ {”和“}”)? 例如,如何防止以下方法調用引發FormatException異常?
result = String.Format("The text has {0} '{' characters and {1} '}' characters.", nOpen, nClose);
單個大括號或大括號始終被解釋為格式項的開頭或結尾。 要從字面上解釋,必須對其進行轉義。 通過添加另一個花括號(“ {{”和“}}”而不是“ {”和“}”)來逃避花括號,如以下方法調用所示:
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.", nOpen, nClose);
但是,即使是逃脫的大括號也容易被誤解。 我們建議您在格式列表中包括括號,並使用格式項將其插入結果字符串,如以下示例所示。
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.", nOpen, "{", nClose, "}");
使用Console.Write("\\'{0}\\' is replaced to '{1}'", "{0}", "Hello");
輸出: '{0}' is replaced to 'Hello'
使用Console.Write("{{0}} is replaced to '{1}'", "{0}", "Hello");
輸出: {0} is replaced to 'Hello'
在C#6
及更高版本中,您可以使用插值字符串 :
string hello = "Hello";
Console.WriteLine($"'{{0}}' is replaced to '{hello}'");
或低於C#6
string hello = "Hello";
Console.WriteLine("'{{0}}' is replaced to '{0}'", hello);
Console.Write("'{{0}}' is replaced to '{0}'", "Hello");
這就是您想要的:
1. Console.WriteLine($"{{0}} is replaced to '{"Hello"}'");
2. Console.WriteLine("{{0}} is replaced to '{0}'","Hello");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.