将字符串拆分为 C 中的子字符串#

小窍门

本文是已了解至少一种编程语言并正在学习 C# 的开发人员的 “基础知识 ”部分的一部分。 如果你不熟悉编程,请先 学习入门 教程。

从另一种语言传入?string.Split是 C# 与 Java 的 String.split 和 JavaScript 的 String.prototype.split 的对应项。 与这些语言不同,C# 返回数组(string[]而不是列表),分隔符参数是字符或字符串,而不是正则表达式。 有关基于模式的拆分,请参阅 Regex.Split

该方法 String.Split 使用一个或多个分隔符将字符串分解为子字符串数组。 这是分析带分隔符的文本(如字词、CSV 样式值或协议令牌)的最简单方法。

该方法有许多重载,但归根结底只涉及四个彼此独立的选择:

  • 分隔符:一个 char、一个数组 char、一 string个或一个数组 string
  • 最大结果计数:限制返回的子字符串数。
  • 空条目处理:保留空子字符串(默认行为),或使用 StringSplitOptions.RemoveEmptyEntries 将其丢弃。
  • 空白字符处理:使用 StringSplitOptions.TrimEntries 去除每个条目前后的空白字符。

将字符串拆分为单词

若要在空格中拆分短语,请传递 ' ' 为分隔符:

string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ');

foreach (var word in words)
{
    Console.WriteLine($"<{word}>");
}
// => <The>
// => <quick>
// => <brown>
// => <fox>
// => <jumps>
// => <over>
// => <the>
// => <lazy>
// => <dog.>

使用 for 遍历返回的数组,以获取每个单词的位置:

string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ');

for (int i = 0; i < words.Length; i++)
{
    Console.WriteLine($"Index {i}: <{words[i]}>");
}
// => Index 0: <The>
// => Index 1: <quick>
// => Index 2: <brown>
// => ...

如果输入包含分隔符的重复实例, Split 则生成空条目,每个连续分隔符之间的“间隙”对应一个:

string phrase = "The quick brown    fox     jumps over the lazy dog.";
string[] words = phrase.Split(' ');

foreach (var word in words)
{
    Console.WriteLine($"<{word}>");
}
// The runs of spaces produce empty entries:
// => <The>
// => <quick>
// => <brown>
// => <>
// => <>
// => <>
// => <fox>
// => ...

传递 StringSplitOptions.RemoveEmptyEntries 以删除这些空条目,如本文后面所示。

按多个分隔字符拆分

当多个字符可以充当分隔符时,将它们作为数组传递。 以下示例将空格、逗号、句点、冒号和制表符视为单词边界:

char[] delimiters = [' ', ',', '.', ':', '\t'];

string text = "one\ttwo three:four,five six seven";
Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(delimiters);
Console.WriteLine($"{words.Length} words in text:");

foreach (var word in words)
{
    Console.WriteLine($"<{word}>");
}
// => 7 words in text:
// => <one>
// => <two>
// => <three>
// => <four>
// => <five>
// => <six>
// => <seven>

相邻分隔符仍生成空条目:

char[] delimiters = [' ', ',', '.', ':', '\t'];

string text = "one\ttwo :,five six seven";
Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(delimiters);
Console.WriteLine($"{words.Length} words in text:");

foreach (var word in words)
{
    Console.WriteLine($"<{word}>");
}
// => 7 words in text:
// => <one>
// => <two>
// => <>
// => <>
// => <five>
// => <six>
// => <seven>

按多字符分隔符拆分

若要按整个单词或多字符分隔符进行拆分,请传入字符串数组。 字符串数组重载需要一个 StringSplitOptions 值。 当重复的分隔符否则会产生空结果时,使用 RemoveEmptyEntries

string[] separators = ["<<", "..."];

string text = "one<<two......three<four";
Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"{words.Length} substrings in text:");

foreach (var word in words)
{
    Console.WriteLine(word);
}
// => 3 substrings in text:
// => one
// => two
// => three<four

限制返回的子字符串数

传递参数 count 以限制结果数。 最后一个条目包含所有剩余内容,包括所有剩余的分隔符:

string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ', 4, StringSplitOptions.None);

foreach (var word in words)
{
    Console.WriteLine($"<{word}>");
}
// => <The>
// => <quick>
// => <brown>
// => <fox jumps over the lazy dog.>

这种模式对于 key=value 对以及其他仅第一个分隔符有意义的格式都很实用。

去除每个条目中的空白字符

StringSplitOptions.TrimEntries 从每个返回的子字符串中去除前导空格和尾随空格。 可以将其与 RemoveEmptyEntries 结合使用,以进行典型的 CSV 风格清理:

string numerals = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
string[] trimmed = numerals.Split(',', StringSplitOptions.TrimEntries);

Console.WriteLine("Trimmed entries:");
foreach (var word in trimmed)
{
    Console.WriteLine($"<{word}>");
}

string[] untrimmed = numerals.Split(',', StringSplitOptions.None);
Console.WriteLine("Untrimmed entries:");
foreach (var word in untrimmed)
{
    Console.WriteLine($"<{word}>");
}
// => Trimmed entries: <1> <2> ... <10>
// => Untrimmed entries: <1> < 2> ... < 10>

使用正则表达式

Split 适用于固定字符或字符串分隔符。 对于基于模式的拆分,请使用 Regex.Split。 有关字符串的正则表达式简介,请参阅 String 操作

另请参阅