Chris
Chris

Reputation: 6780

Auto-Generate place holder format string for String.Format()

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

Answers (4)

brgerner
brgerner

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

Reed Copsey
Reed Copsey

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

shahkalpesh
shahkalpesh

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

David Andres
David Andres

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

Related Questions