【发布时间】:2011-12-14 18:51:45
【问题描述】:
这个任务最优雅的解决方案是什么:
有一个模板字符串,例如:"<CustomAction Id=<newGuid> /><CustomAction Id=<newGuid> />",我需要用不同的Guid替换<newGuid>。
概括问题:
.Net 字符串类具有 Replace 方法,该方法采用 2 个参数:字符或字符串类型的 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有类似的签名。可能会更好用。 -
Regex.Replace 让您指定回调,但您必须转义搜索字符串。
-
终于明白他的意思了,他希望每次替换出现都是函数调用结果的不同值...问题没有正确编写,没有示例说明解决方案应该如何工作。