What is the most elegant solution for this task:
There is a template string, for example: "<CustomAction Id=<newGuid> /><CustomAction Id=<newGuid> />"
and I need to replace <newGuid>
by different Guids.
Generalize the problem:
.Net string class has Replace method that takes 2 parameters: oldValue and newValue of char or string type. Problem is that newValue is static string (not a function returning string).
There is my simple implementation:
public static string Replace(this string str, string oldValue, Func<String> newValueFunc)
{
var arr = str.Split(new[] { oldValue }, StringSplitOptions.RemoveEmptyEntries);
var expectedSize = str.Length - (20 - oldValue.Length)*(arr.Length - 1);
var sb = new StringBuilder(expectedSize > 0 ? expectedSize : 1);
for (var i = 0; i < arr.Length; i++)
{
if (i != 0)
sb.Append(newValueFunc());
sb.Append(arr[i]);
}
return sb.ToString();
}
Can you suggest more elegant solution?