Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to convert C-format strings for C# -format strings in C#/.NET 2.0?

So i would like to convert string like this:

"Bloke %s drank %5.2f litres of booze and ate %d bananas"

with a C# equivalent for .Format or .AppendFormat methods

"Bloke {0} drank {1,5:f2} litres of booze and ate {2} bananas"

sorry but i'm not sure if the C# version was correct but u got the idea. The solution does not have to be perfect but cover the basic case.

Thanks & BR -Matti

answered in my other question How to write C# regular expression pattern to match basic printf format-strings like "%5.2f"?

like image 772
char m Avatar asked Nov 06 '22 07:11

char m


1 Answers

You could probably just use StringBuilder.Replace().

StringBuilder cString = new StringBuilder("Bloke %s drank %5.2f litres of booze and ate %d bananas");
cString.Replace("%s","{0}");
cString.Replace("%5.2f", "1,5:f2"); // I am unsure of this format specifier
cString.Replace("%d", "{2}");

string newString = String.Format(cString.ToString(), var1, var2, var3);

Conceivably you could add something like this to as an extension method to String, but I think your biggest problem is going to be the specially formatted specifiers. If it is non-trivial in this aspect, you may need to devise a regular expression to catch those and perform the replace meaningfully.

like image 105
Joel Etherton Avatar answered Nov 09 '22 13:11

Joel Etherton