How to escape braces (curly brackets) in a format

2018-12-31 06:21发布

How can brackets be escaped in using string.Format. For example:

String val = "1,2,3"
String.Format(" foo {{0}}", val); 

This example doesn't throw an exception, but outputs the string foo {0}

Is there a way to escape the brackets?

9条回答
伤终究还是伤i
2楼-- · 2018-12-31 06:51

Escaping curly brackets AND using string interpolation makes for an interesting challenge. You need to use quadruple brackets to escape the string interpolation parsing and string.format parsing.

Escaping Brackets: String Interpolation $("") and String.Format

string localVar = "dynamic";
string templateString = $@"<h2>{0}</h2><div>this is my {localVar} template using a {{{{custom tag}}}}</div>";
string result = string.Format(templateString, "String Interpolation");

// OUTPUT: <h2>String Interpolation</h2><div>this is my dynamic template using a {custom tag}</div>
查看更多
伤终究还是伤i
3楼-- · 2018-12-31 06:56

You can use double open brackets and double closing brackets which will only show one bracket on your page.

查看更多
怪性笑人.
4楼-- · 2018-12-31 06:59

For you to output foo {1, 2, 3} you have to do something like:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

To output a { you use {{ and to output a } you use }}.

查看更多
登录 后发表回答