如何:拆分字符串(C# 编程指南)

下面的代码示例演示如何使用 String.Split 方法分析字符串。 作为输入,Split 采用一个字符数组指示哪些字符被用作分隔符。 本示例中使用了空格、逗号、句点、冒号和制表符。 一个含有这些分隔符的数组被传递给 Split,并使用结果字符串数组分别显示句子中的每个单词。

示例

class TestStringSplit
{
    static void Main()
    {
        char[] delimiterChars = { ' ', ',', '.', ':', '\t' };

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

        string[] words = text.Split(delimiterChars);
        System.Console.WriteLine("{0} words in text:", words.Length);

        foreach (string s in words)
        {
            System.Console.WriteLine(s);
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    Original text: 'one     two three:four,five six seven'
    7 words in text:
    one
    two
    three
    four
    five
    six
    seven
 */

请参见

概念

C# 编程指南

其他资源

字符串(C# 编程指南)

.NET Framework 正则表达式