,这是什么任务最优雅的解决方案:实施建议与string.replace(字符串属性oldValue,Func键<string> NEWVALUE)功能
有一个模板字符串,例如:"<CustomAction Id=<newGuid> /><CustomAction Id=<newGuid> />"
,我需要通过不同的更换<newGuid>
的GUID。
一般化问题:
净串类有替换方法,该方法需要两个参数:属性oldValue和焦炭或字符串类型NEWVALUE。问题是newValue是静态字符串(不是返回字符串的函数)。
还有就是我的简单的实现:
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();
}
您能否提供更好的解决方案?
'Regex.Replace'有类似的签名。可能会更好地使用。 – leppie
Regex.Replace让我们指定一个回调,但你必须转义搜索字符串。 –
谢谢,这是我想要的。 –