Is there a way to String.Format
a message without having to specify {1}, {2},
etc? Is it possible to have some form of auto-increment? (Similar to plain old printf
)
views:
389answers:
4
+1
A:
Afraid not -- where would it put the objects into the string? Using printf, you still need to put specifiers in somewhere.
mquander
2009-02-18 13:59:27
Yes, I don't mind using specifiers, but I don't want to hard-code the indices.
Hosam Aly
2009-02-18 14:02:15
@Hosam - is this for the purpose of embedding other formattable strings within formattable strings and then adding all the params at a later stage?
BenAlabaster
2009-02-18 14:06:03
@balabaster: no, it's one call to `String.Format` to insert a few variables.
Hosam Aly
2009-02-18 14:16:42
+2
A:
You can use a named string formatting solution, which may solve your problems.
cbp
2009-02-18 14:01:09
A:
One could always use this (untested) method, but I feel it's over complex:
public static string Format(char splitChar, string format,
params object[] args)
{
string splitStr = splitChar.ToString();
StringBuilder str = new StringBuilder(format + args.Length * 2);
for (int i = 0; i < str.Length; ++i)
{
if (str[i] == splitChar)
{
string index = "{" + i + "}";
str.Replace(splitStr, index, i, 1);
i += index.Length - 1;
}
}
return String.Format(str.ToString(), args);
}
Hosam Aly
2009-02-18 14:14:34