首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

.NET 字串替換的五種方法與效能比較

     編輯:關於C語言

五種替換方式概覽

  1. String.Replace:簡單易用,但不支援大小寫不敏感。
  2. Regex.Replace:支援正則表達式與 RegexOptions.IgnoreCase,功能強大但效能較低。
  3. String.Substring + 串接:適用小資料量,手動控制替換邏輯。
  4. Microsoft.VisualBasic.Strings.Replace:引用 VB Runtime,速度快且支援大小寫選項。
  5. 反射配合 Split/Join:效能與第 4 種相近。

自訂高效能替換演算法 (ReplaceEx)

參考 KMP 思想,先轉大寫比對索引,再以 char[] 陣列一次建構結果,避免重複字串配置:

private static string ReplaceEx(string original, string pattern, string replacement)
{
    int count = 0, position0 = 0, position1 = 0;
    string upperString = original.ToUpper();
    string upperPattern = pattern.ToUpper();
    int inc = (original.Length / pattern.Length) * (replacement.Length - pattern.Length);
    char[] chars = new char[original.Length + Math.Max(0, inc)];

    while ((position1 = upperString.IndexOf(upperPattern, position0)) != -1)
    {
        for (int i = position0; i < position1; ++i) chars[count++] = original[i];
        for (int i = 0; i < replacement.Length; ++i) chars[count++] = replacement[i];
        position0 = position1 + pattern.Length;
    }
    if (position0 == 0) return original;
    for (int i = position0; i < original.Length; ++i) chars[count++] = original[i];
    return new string(chars, 0, count);
}

效能測試結果 (1000 次迭代)

測試字串RegexVB ReplaceReplaceExString.Replace
"AaBbCc" x10003.75 秒1.46 秒0.80 秒0.18 秒
"abcaBcabC" x10005.30 秒2.50 秒1.01 秒0.23 秒
"ABCabcAbCaBcAbcabCABCAbcaBC" x100013.59 秒11.18 秒1.70 秒0.42 秒

結論:若需大小寫不敏感且追求效能,ReplaceEx 優於 Regex 與 VB Replace;若區分大小寫,內建 String.Replace 最快。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved