,這是什麼任務最優雅的解決方案:實施建議與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讓我們指定一個回調,但你必須轉義搜索字符串。 –
謝謝,這是我想要的。 –