How to: Parse Strings Using the Split Method (C#)

Switch View :
ScriptFree
C# Programming Guide
How to: Parse Strings Using the Split Method (C# Programming Guide)

The following code example demonstrates how a string can be parsed using the System.String.Split method. This method works by returning an array of strings, where each element is a word. As input, Split takes an array of chars that indicate which characters are to be used as delimiters. In this example, spaces, commas, periods, colons, and tabs are used. An array containing these delimiters is passed to Split, and each word in the sentence is displayed separately using the resulting array of strings.

Example

C#
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);
        }
    }
}

Output

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

See Also

Community Content

Akintunde
Useful overloads
It may also be useful to know of one of the particular Split overloads: Split(delimiters, StringSplitOptions).  You can specify StringSplitOptions.RemoveEmptyEntries to get rid of any empty returns you likely would not want.