// 內建用法
string[] parts = "a,b,c".Split(','); // 單一字元
string[] parts = "a,b,c".Split(new char[]{','}); // 字元陣列
// 無法直接: "a::b::c".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"]
// 自訂 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[] separatorsSplit(ReadOnlySpan) 避免字串配置 (.NET Core 2.1+)