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

示例

C# CopyCode image复制代码
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);
        }
    }
}

输出

 
Original text: 'one     two three:four,five six seven'
7 words in text:
one
two
three
four
five
six
seven

请参见

概念

C# 编程指南

其他资源

字符串(C# 编程指南)
.NET Framework 正则表达式
使用 C++ 进行 .NET 编程