This extension method is not limited to a fixed number of parameters. That is it will work with strings like "{0}"
, but also "{0} {1}"
, "{0} {1} {2}"
and so on.
The minor disadvantage is that first you give optional argument and then the non-optional. Should be the other way around but unfortunately the nature of the params
keyword prohibits that.
The major disadvantage is that it ignores the number in the curly braces (though the solution can be reworked to include that as well).
public static string FormatOpt(this string s, string optional, params string[] param)
{
StringBuilder result = new StringBuilder();
int index = 0;
bool opened = false;
Stack<string> stack = new Stack<string>(param.Reverse());
foreach(var c in s)
{
if (c == '{')
{
opened = true;
index = result.Length;
}
else if (opened && c == '}')
{
opened = false;
var p = stack.Count > 0 ? stack.Pop() : optional;
var lenToRem = result.Length - index;
result.Remove(index, lenToRem);
result.Append(p);
continue;
}
else if (opened && !Char.IsDigit(c))
{
opened = false;
}
result.Append(c);
}
return result.ToString();
}
And there are expected results:
string res1 = "result: {0}, {1}, {2}, {3}".FormatOpt("optional", "first param", "second param");
// result: first param, second param, optional, optional
string res2 = "result: {0}, {1}, {2}, {3}".FormatOpt("optional", "first param");
// result: first param, optional, optional, optional
string res3 = "result: {0}, {1}, {2}, {3}".FormatOpt("optional");
// result: optional, optional, optional, optional
String.Format
, what exactly are you trying to achieve, may be you can useString.Join
to concatenate unknown numbers of string elements. – Jaret