Share via


HOW TO:分割字串 (C# 程式設計手冊)

下列程式碼範例示範如何使用 String.Split 方法剖析字串。 當輸入時,Split 會採用字元陣列以表示用來當做分隔符號 (Delimiter) 的字元。 在這個範例中會使用空格、逗號、句號、冒號和索引標籤。 包含這些分隔符號的陣列會傳遞至 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 規則運算式

其他資源

.NET 程式設計指南