找到一個在這裏評論:http://www.codeproject.com/Messages/1835929/this-one-is-even-faster-and-more-flexible-modified.aspx
static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType)
{
return Replace(original, pattern, replacement, comparisonType, -1);
}
static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType, int stringBuilderInitialSize)
{
if (original == null)
{
return null;
}
if (String.IsNullOrEmpty(pattern))
{
return original;
}
int posCurrent = 0;
int lenPattern = pattern.Length;
int idxNext = original.IndexOf(pattern, comparisonType);
StringBuilder result = new StringBuilder(stringBuilderInitialSize < 0 ? Math.Min(4096, original.Length) : stringBuilderInitialSize);
while (idxNext >= 0)
{
result.Append(original, posCurrent, idxNext - posCurrent);
result.Append(replacement);
posCurrent = idxNext + lenPattern;
idxNext = original.IndexOf(pattern, posCurrent, comparisonType);
}
result.Append(original, posCurrent, original.Length - posCurrent);
return result.ToString();
}
應該是最快的,但我沒有檢查。
否則,你應該做西蒙建議和使用VisualBasic Replace函數。這是我總是做的,因爲它的大小寫不敏感的功能(我通常是一個VB.Net程序員)。
string s = "SoftWare";
s = Microsoft.VisualBasic.Strings.Replace(s, "software", "hardware", 1, -1, Constants.vbTextCompare);
您必須添加對Microsoft.VisualBasic dll的引用。
看一看這裏的討論:http://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive。有一個擴展方法的例子,它會做你想做的。 – 2011-04-05 09:04:29
@RB:謝謝,這是「擴展」.Net功能的好方法,但我的查詢是關於是否有內置方法。儘管我會用這個例子來包裝我的Regex replace,歡呼聲。 – 2011-04-05 09:27:32