views:

67

answers:

1

Using .NET string formatting you can plug the same value into a format string multiple times:

Console.Write("{0}{0}{0}", 1) //prints "111"

Is there any way to do this with printf-style formatting, supplying the value only once?

+1  A: 

No. The values are taken in order, from the stack, when passed to the function. If you want multiple appearances of the same value if different parts of the string, you have to supply them in order, multiple times.

Think of it this way: you have a string, with markers, and a list of things to insert replacing those markers. As the list has to be in order of appearance, if you want to replace two markers with the same value, the value has to show up twice.

Now, keep in mind that duplicating the parameter doesn't necessarily mean duplicating the actual data.

Santiago Lezica
.NET string formatting is looking pretty sexy right now.
Daniel
@Daniel - that's a sentence I didn't ever expect to read...
kvb
I never expected I would say it.
Daniel
I'm generating SQL and joining to the same table a lot. I hate typing that table name over and over. Was hoping for some help from printf on this. But since I have to trade type inference for less typing, I guess I'll begrudgingly take type inference.
Daniel
Python is the king of metaprogramming, I create most of my boilerplate code using short (< 10 lines) Python programs. Try that the next time and see if you like it!
Santiago Lezica
Aside: I think we may have reserved operators-beginning-with-`$` or something like that specifically so that in some future version we might add e.g. syntax like `$"foo: $bar $qux $bar"` where `$name` injects the value of `name` from the environment into the `$`string literal. To be clear, we have no actual plans for doing this in the short term, but we explicitly reserved some kind of empty space in the language grammar design to possibly do stuff like this in the future. "Scripting" in general often lends itself well to wanting shorthand/niceties in string formatting.
Brian
@Brian - String interpolation seems like it would fit great with F#.
Daniel