How do I split a string?

Category: System, viewed: 4K time(s).

This example demonstrate how to split a csv (comma separated value) string. The String.Split() returns the splitted data as an array of string.

using System;

namespace Kodecsharp.Example.System
{
    public class StringSplit
    {
        public static void Main(string[] args)
        {
            string row = "0001,Foo,Bar,California Bay,1976";

            //
            // Returns a string array that contains the substrings in this 
            // instance that are delimited by elements of a specified 
            // Unicode character array. 
            //
            string[] fields = row.Split(',');
            foreach (string field in fields) 
            {
                Console.WriteLine(field);
            }

            row = "The quick,brown:fox;jumps over the lazy dog";
            char[] delimiters = { ' ', ',', ':' };

            //
            // Returns a string array that contains the substrings in this 
            // instance that are delimited by elements of a specified Unicode 
            // character array. A parameter specifies the maximum number of 
            // substrings to return. 
            //
            fields = row.Split(delimiters, 6);
            foreach (string field in fields)
            {
                Console.WriteLine(field);
            }
        }
    }
}

The result of our code can be seen below.

0001
Foo
Bar
California Bay
1976
The
quick
brown
fox;jumps
over
the lazy dog
Powered by Disqus