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条回答
浅入江南
2楼-- · 2018-12-31 06:39

Almost there! The escape sequence for a brace is {{ or }} so for your example you would use:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 06:42
[TestMethod]
public void BraceEscapingTest()
{
    var result = String.Format("Foo {{0}}", "1,2,3");  //"1,2,3" is not parsed
    Assert.AreEqual("Foo {0}", result);

    result = String.Format("Foo {{{0}}}", "1,2,3");
    Assert.AreEqual("Foo {1,2,3}", result);

    result = String.Format("Foo {0} {{bar}}", "1,2,3");
    Assert.AreEqual("Foo 1,2,3 {bar}", result);

    result = String.Format("{{{0:N}}}", 24); //24 is not parsed, see @Guru Kara answer
    Assert.AreEqual("{N}", result);

    result = String.Format("{0}{1:N}{2}", "{", 24, "}");
    Assert.AreEqual("{24.00}", result);

    result = String.Format("{{{0}}}", 24.ToString("N"));
    Assert.AreEqual("{24.00}", result);
}
查看更多
荒废的爱情
4楼-- · 2018-12-31 06:43

Yes to output { in string.Format you have to escape it like this {{

So this

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

will output "foo {1,2,3}".

BUT you have to know about a design bug in C# which is that by going on the above logic you would assume this below code will print {24.00}

int i = 24;
string str = String.Format("{{{0:N}}}", i); //gives '{N}' instead of {24.00}

But this prints {N}. This is because the way C# parses escape sequences and format characters. To get the desired value in the above case you have to use this instead.

String.Format("{0}{1:N}{2}", "{", i, "}") //evaluates to {24.00}

Reference Articles String.Format gottach and String Formatting FAQ

查看更多
唯独是你
5楼-- · 2018-12-31 06:43

Came here in search of how to build json strings ad-hoc (without serializing a class/object) in C#. In other words, how to escape braces and quotes while using Interpolated Strings in C# and "verbatim string literals" (double quoted strings with '@' prefix), like...

var json = $@"{{""name"":""{name}""}}";
查看更多
大哥的爱人
6楼-- · 2018-12-31 06:43

or you can use c# string interpolation like this (feature available in C# 6.0)

var value = "1, 2, 3";
var output = $" foo {{{value}}}";
查看更多
听够珍惜
7楼-- · 2018-12-31 06:50

Please do not use string.Format. Currently there is a better way to formatting string that more understandable.

查看更多
登录 后发表回答