Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escaping curly braces for string.format [duplicate]

Tags:

c#

void f(string message)
{
    string.Format(message,"x",y");
}

f() is called by g:

g()
{
   f(SomeJson+"{0}");
}

the curly braces in json are being interpreted as placeholders for values by string.format() in f(). IS there a way to have the curly braces escaped?

like image 368
Aadith Ramia Avatar asked Aug 15 '26 04:08

Aadith Ramia


1 Answers

Double them up:

f(SomeJson+"{{0}}");

Or replace them in the JSON, if that's what you need:

f(SomeJson.Replace("{", "{{")
    .Replace("}", "}}") + "{0}");

You could also delegate this job to an extension method:

public static class StringExtensions
{
    public static string EscapeBraces(this string s)
    {
        return s.Replace("{", "{{")
                .Replace("}", "}}");
    }
}

f(SomeJson.EscapeBraces() + "{0}");

Or, as Ergwun says, you could simply concatenate the values afterwards. My assumption, though, is that that's less straightforward in your actual code than in this trivial example.

like image 180
Ant P Avatar answered Aug 17 '26 19:08

Ant P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!