Reputation: 6780
Is there a way to tell the String.Format()
function (without writing my own function) how many placeholders there are dynamically? It we be great to say 15
, and know I'd have {0}-{14}
generated for me. I'm generate text files and I often have more than 25 columns. It would greatly help.
OK,
I will rephrase my question. I wanted to know if it is at all possible to tell the String.Format
function at execution time how many place-holders I want in my format string without typing them all out by hand.
I'm guessing by the responses so far, I will just go ahead and write my own method.
Thanks!
Upvotes: 0
Views: 1498
Reputation: 4371
You could use Enumerable.Range and LINQ to generate your message string.
Enumerable.Range(0, 7).Select(i => "{" + i + "}").ToArray()
generates following string:
"{0}{1}{2}{3}{4}{5}{6}"
Upvotes: 3
Reputation: 564641
There is a way to do this directly:
Just create a custom IFormatProvider, then use this overload of string.Format.
For example, if you want to always have 12 decimal points, you can do:
CultureInfo culture = Thread.CurrentThread.CurrentCulture.Clone(); // Copy your current culture
NumberFormatInfo nfi = culture.NumberFormat;
nfi.NumberDecimalDigits = 12; // Set to 12 decimal points
string newResult = string.Format(culture, "{0}", myDouble); // Will put it in with 12 decimal points
Upvotes: 0
Reputation: 33474
Why use string.Format
when there is no formatting (atleast from what I can see in your question)? You could use simple concatenation using stringbuilder instead.
Upvotes: 1
Reputation: 31781
Adding a bit to AlbertEin's response, I don't believe String.Format
can do this for you out-of-the-box. You'll need to dynamically create the format string prior to using the String.Format
method, as in:
var builder = new StringBuilder();
for(var i = 0; i < n; ++i)
{
builder.AppendFormat("{0}", "{" + i + "}");
}
String.Format(builder.ToString(), ...);
This isn't exactly readable, though.
Upvotes: 1