字串分割是程式開發中極高頻的操作。C# 提供 `String.Split`、`String.Split(char[])`、`Regex.Split` 等多種方式,各有適用情境與效能差異。本文系統整理各種分割技巧、常見陷阱、效能比較與最佳實務。
string s = "abcdeabcdeabcde";
string[] parts = s.Split('c');
// 結果: ["ab", "deab", "deab", "de"]
string s = "abcdeabcdeabcde";
// 以 c、d、e 任一字元分割
string[] parts = s.Split(new char[] { 'c', 'd', 'e' }, StringSplitOptions.RemoveEmptyEntries);
// 結果: ["ab", "ab", "ab"] (移除空項)
StringSplitOptions:
.NET Core / .NET 5+ 支援字串陣列做分隔符:
string s = "apple||orange&&banana";
string[] parts = s.Split(new string[] { "||", "&&" }, StringSplitOptions.RemoveEmptyEntries);
// 結果: ["apple", "orange", "banana"]
.NET Framework 4.x 需自行實作或用 Regex。
using System.Text.RegularExpressions;
string content = "agcsmallmacsmallgggsmallytx";
string[] result = Regex.Split(content, "small", RegexOptions.IgnoreCase);
// 結果: ["agc", "mac", "ggg", "ytx"]
// 分割「一或多個空白字元」
string[] words = Regex.Split(input, @"\s+");
// 分割「逗號、分號、管線符號」及其前後空白
string[] items = Regex.Split(input, @"\s*[,;|]\s*");
// 分割「HTML 標籤」
string[] textParts = Regex.Split(html, @"<[^>]+>");
優點:支援複雜模式、不區分大小寫、前後預測。
缺點:效能較差、正則寫錯難除錯。
原文提到的 `[jb51.net]` 替換法屬於變通做法。若需分割並保留分隔符,可用 Regex 捕獲群組:
string str = "reterry[jb51.net]是腳本之家[jb51.net]的站長";
// 保留分隔符
string[] parts = Regex.Split(str, @"(\[jb51\.net\])");
// 結果: ["reterry", "[jb51.net]", "是腳本之家", "[jb51.net]", "的站長"]
| 方法 | 耗時 (ms) | 相對效能 | 適用場景 |
|---|---|---|---|
| Split(char) | ~45 | 1.0x (基準) | 單一字元分隔、高效能需求 |
| Split(char[], RemoveEmptyEntries) | ~65 | 1.4x | 多字元分隔、需移除空項 |
| Split(string[]) | ~120 | 2.7x | 字串分隔符 (.NET Core+) |
| Regex.Split (簡單模式) | ~480 | 10.7x | 複雜模式、不區分大小寫 |
| Regex.Split (複雜模式) | ~1200+ | 26x+ | 極複雜模式、最後手段 |
結論:能用 `Split(char)` 或 `Split(char[])` 就不要用 `Regex.Split`。只有在分隔符為變長字串、需忽略大小寫、或需前後預測時才使用 Regex。
s.Split(",") 會被編譯器視為 `Split(char[])`,將逗號拆成字元陣列,導致以 `,` 分割而非 `","`。正確寫法:s.Split(new[] { "," }, StringSplitOptions.None)。public static class StringExtensions
{
public static string[] SplitEx(this string str, string separator, StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries)
{
if (string.IsNullOrEmpty(str)) return Array.Empty();
return str.Split(new[] { separator }, options);
}
public static string[] SplitEx(this string str, string[] separators, StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries)
{
if (string.IsNullOrEmpty(str)) return Array.Empty();
return str.Split(separators, options);
}
}
// 簡易 CSV 行分割 (不處理引號逸出,生產環境請用 CsvHelper 套件)
string csvLine = "張三,25,\"台北市,信義區\",工程師";
string[] fields = Regex.Split(csvLine, @",(?=(?:[^""]*""[^""]*"")*[^""]*$)");
// 結果: ["張三", "25", "\"台北市,信義區\"", "工程師"]
總結:C# 字串分割首選 `Split(char[])` 搭配 `StringSplitOptions.RemoveEmptyEntries`,兼顧效能與可讀性。複雜分割模式才使用 `Regex.Split`,並注意編譯緩存 (`RegexOptions.Compiled`)。避免原文中以字元陣列拆解特定字串的反模式,善用正則捕獲群組或字串替換技巧。