Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format certain argument

I would assume this is a common question but I couldn't seem to find anything on SO or google.

Is it possible to only format a single argument. For example, format string foo = "{0} is {1} when {2}"; so that it returns read "{0} is cray when {2}"?

Intentions:
I am trying to format the string while overriding a method before it gets formatted in it's base method

Success
Got it thanks to this answer, all answers were helpful :).

This unit test worked:

string foo = String.Format("{0} is {1} when {2}", "{0}", "cray", "{2}");
Assert.AreEqual("{0} is cray when {2}", foo);
string bar = string.Format(foo, "this", null, "it works");
Assert.AreEqual("this is cray when it works", bar);
like image 430
MrJD Avatar asked Feb 19 '23 07:02

MrJD


2 Answers

Taking your question at face value, I suppose you could do the following:

string foo = String.Format("{0} is {1} when {2}", "{0}", "cray", "{2}");

That is, simply replace each unevaluated format item with itself.

like image 183
Paul Bellora Avatar answered Feb 21 '23 01:02

Paul Bellora


No, this is not possible. String.Format is going to try and replace every bracketed placeholder. If you do not supply the correct number of arguments, an exception will be raised.

I'm not sure why you are trying to do this, but if you want the output to look like that, you'll have to escape the brackets:

var foo = String.Format("{{0}} is {0} when {{1}}", "cray");
// foo is "{0} is cray when {1}"

Perhaps if you tell us what exactly you're trying to do, we'll be able to better help you.

like image 22
Jonathon Reinhart Avatar answered Feb 21 '23 02:02

Jonathon Reinhart