2011-10-25 33 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"; 
    } 
}