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

使用 C# 自寫 Split 函數支援字串分隔符:突破內建僅支援字元陣列的限制

     編輯:關於C語言

痛點:String.Split 僅支援 char/char[] 分隔符


// 內建用法
string[] parts = "a,b,c".Split(',');           // 單一字元
string[] parts = "a,b,c".Split(new char[]{','}); // 字元陣列
// 無法直接: "a::b::c".Split("::") // 編譯錯誤

自訂字串分隔符 Split 實作


using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public static class StringExtensions
{
    public static string[] Split(this string source, string separator)
    {
        if (string.IsNullOrEmpty(separator))
            return new[] { source };

        var result = new List();
        int start = 0, idx;
        while ((idx = source.IndexOf(separator, start)) != -1)
        {
            result.Add(source.Substring(start, idx - start));
            start = idx + separator.Length;
        }
        result.Add(source.Substring(start));
        return result.ToArray();
    }
}

// 使用
string[] parts = "a::b::c".Split("::"); // ["a", "b", "c"]

效能比較 (1000 次迴圈)


// 自訂 Split
DateTime t1 = DateTime.Now;
for (int i=0;i<1000;i++) "a::b::c".Split("::");
TimeSpan custom = DateTime.Now - t1;

// Regex.Split
Regex rg = new Regex("::");
DateTime t2 = DateTime.Now;
for (int i=0;i<1000;i++) rg.Split("a::b::c");
TimeSpan regex = DateTime.Now - t2;

Console.WriteLine($"Custom: {custom.TotalMilliseconds}ms, Regex: {regex.TotalMilliseconds}ms");

自訂索引法通常比 Regex 快 3-5 倍,且無正則表達式編譯開銷。

擴充建議

  • 加入 StringSplitOptions.RemoveEmptyEntries 參數支援
  • 支援多重分隔符 params string[] separators
  • 實作 Split(ReadOnlySpan) 避免字串配置 (.NET Core 2.1+)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved