How to escape braces (curly brackets) in a format string in .NET

后端 未结 10 2346
不思量自难忘°
不思量自难忘° 2020-11-22 02:44

How can brackets be escaped in using string.Format.

For example:

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

相关标签:
10条回答
  • 2020-11-22 03:32

    My objective:

    I needed to assign the value "{CR}{LF}" to a string variable delimiter.

    Code c#:

    string delimiter= "{{CR}}{{LF}}";
    

    Note: To escape special characters normally you have to use . For opening curly bracket {, use one extra like {{. For closing curly bracket }, use one extra }}.

    0 讨论(0)
  • 2020-11-22 03:34
    [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);
    }
    
    0 讨论(0)
  • 2020-11-22 03:34

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

    var value = "1, 2, 3";
    var output = $" foo {{{value}}}";
    
    0 讨论(0)
  • 2020-11-22 03:35

    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);
    
    0 讨论(0)
提交回复
热议问题