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"?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With