对于此任务,最优雅的解决方案是什么:
有一个模板字符串,例如:"<CustomAction Id=<newGuid> /><CustomAction Id=<newGuid> />"和我需要用不同的Guids替换<newGuid>。
概括问题:
.Net string类有一个带有两个参数的Replace方法:字符或字符串类型的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();
}你能推荐更优雅的解决方案吗?
发布于 2011-10-25 20:12:16
我认为是时候总结一下了,以避免错误的答案。
最优雅的解决方案是由leppie和Henk Holterman提出的
public static string Replace(this string str, string oldValue, Func<string> newValueFunc)
{
return Regex.Replace( str,
Regex.Escape(oldValue),
match => newValueFunc() );
} 发布于 2011-10-25 19:44:56
这对我来说很有效:
public static string Replace(this string str, string oldValue,
Func<String> newValueFunc)
{
var arr = str.Split(new[] { oldValue }, StringSplitOptions.None);
var head = arr.Take(1);
var tail =
from t1 in arr.Skip(1)
from t2 in new [] { newValueFunc(), t1 }
select t2;
return String.Join("", head.Concat(tail));
}如果我从这个开始:
int count = 0;
Func<string> f = () => (count++).ToString();
Console.WriteLine("apple pie is slappingly perfect!".Replace("p", f));然后我得到这样的结果:
a01le 2ie is sla34ingly 5erfect!发布于 2011-10-25 20:14:26
使用
Regex.Replace(String,MatchEvaluator)
using System;
using System.Text.RegularExpressions;
class Sample {
// delegate string MatchEvaluator (Match match);
static public void Main(){
string str = "<CustomAction Id=<newGuid> /><CustomAction Id=<newGuid> />";
MatchEvaluator myEvaluator = new MatchEvaluator(m => newValueFunc());
Regex regex = new Regex("newGuid");//OldValue
string newStr = regex.Replace(str, myEvaluator);
Console.WriteLine(newStr);
}
public static string newValueFunc(){
return "NewGuid";
}
}https://stackoverflow.com/questions/7887117
复制相似问题