0

I have a string var str1 = "My name is {{0}}, I am {{1}} years old." I want to use String.Format(str1, 'Pavel', 29);

Of course it does not work, because String.Format() expects parameter placeholders to be in a single curly brackets

So, I have to modify my string like that:

for (int i = 0; i < 10; i++)
{
    str1 = str1.Replace("{{" + i + "}}", "{" + i + "}");
}

I wonder if there is a better way of doing it ? Is there a way I can define the format of the argument placeholders ?

3
  • you can supply the "outer" { and } as params Commented Jan 24, 2018 at 16:25
  • Why does the original str1 have double braces in it to begin with? Is it supplied to you from somewhere you do not control? Commented Jan 24, 2018 at 17:41
  • @Mike, exactly. Commented Jan 24, 2018 at 17:54

1 Answer 1

1

Is there a way I can define the format of the argument placeholders?

No.

I wonder if there is a better way of doing it?

The only option you have is to make a format string that is compatible with string.Format. And that is what you have done now. If you can, fix the origin of those format strings.

If that is not possible, I would opt to use a regular expression to make this more robust and better performing.

The expression you should use is {{(\d+)}}, which can be replaced with {$1}. See it in action here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.