How to: Parse Strings Using String.Split (C# Programming Guide)

 

Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The following code example demonstrates how a string can be parsed using the String.Split method. As input, Split takes an array of characters that indicate which characters separate interesting sub strings of the target string. The function returns an array of the sub strings.

This example uses spaces, commas, periods, colons, and tabs, all passed in an array containing these separating characters to Split. Each word in the target string's sentence displays separately from the resulting array of strings.

    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
     */

By default, String.Split returns empty strings when two separating characters appear contiguously in the target string. You can pass an optional StringSplitOptions.RemoveEmptyEntries parameter to exclude any empty strings in the output.

String.Split can take an array of strings (character sequences that act as separators for parsing the target string, instead of single characters).

class TestStringSplit  
{  
    static void Main()  
    {  
        char[] separatingChars = { "<<", "..." };  
  
        string text = "one<<two......three<four";  
        System.Console.WriteLine("Original text: '{0}'", text);  
  
        string[] words = text.Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries );  
        System.Console.WriteLine("{0} substrings 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'  
    3 words in text:  
    one  
    two  
    three<four  
*/  
  

C# Programming Guide
Strings
.NET Framework Regular Expressions

Show: