2011-10-25 25 views
3

,这是什么任务最优雅的解决方案:实施建议与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(); 
    } 

您能否提供更好的解决方案?

+2

'Regex.Replace'有类似的签名。可能会更好地使用。 – leppie

+1

Regex.Replace让我们指定一个回调,但你必须转义搜索字符串。 –

+0

谢谢,这是我想要的。 –

回答

1

我认为这是一次总结,以避免错误的答案...

最优雅的解决方案建议通过leppieHenk Holterman

public static string Replace(this string str, string oldValue, Func<string> newValueFunc) 
{ 
    return Regex.Replace(str, 
         Regex.Escape(oldValue), 
         match => newValueFunc()); 
} 
+3

此答案无效。尝试'“t.e.s.t。”。替换(“。”,()=>“\\\\”)或者替换(“。”,()=>“x”)''。返回应该如下所示:'return Regex.Replace(str,Regex.Escape(oldValue),match => newValueFunc());'。 – Enigmativity

+0

@Enigmativity,Ooops)。感谢您的评论。 –

+0

我不明白,是不是什么字符串。更换已经?替换另一个字符串发生? –

0

这个工作对我来说:

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! 
+0

是的,它可以工作,这是我想要的,但由leppie和HenkHolterman建议的'Regex.Replace'更加优雅。 –

+0

是的,你是对的 - 'RegEx'方法是最好的 - 当它工作。你需要检查我放回答案的评论。 – Enigmativity

0

使用

Regex.Replace(字符串,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"; 
    } 
}