Start learning free

LESSON 62 OF 347 · STRINGS I

String Split in C#: Splitting Into an Array

Lesson Read the full explanation

In Java, you can split a string into an array of substrings using split(). It takes a regular expression as the delimiter:

s.Split(separator)   // splits using a separator

Here are some examples:

string sentence = "hello world foo";
string[] words = sentence.Split(' ');
// words == ["hello", "world", "foo"]

string csv = "a,b,c";
string[] parts = csv.Split(',');
// parts == ["a", "b", "c"]

You can loop through the resulting array:

foreach (string w in words) {
    Console.WriteLine(w);
}

Assignment
Follow the Coding Tutorial and split sentence into a String array!


Hint
Use sentence.split(" ") and assign the result to words.

STEP 1 OF 1
    Ctrl + Enter to check

    C# · STRINGS I

    String Split in C#, explained

    Breaking a string apart

    The Split method cuts a string at every separator and returns the pieces as a string[]. The separators themselves are not part of the pieces.

    string sentence = "hello world foo";
    string[] words = sentence.Split(' ');
    // words holds "hello", "world", "foo"
    
    string csv = "a,b,c";
    string[] parts = csv.Split(',');
    // parts holds "a", "b", "c"
    

    A separator written with single quotes is a char. The result is an array, so words.Length is 3 and words[0] is "hello". The original string is not changed.

    Looping over the pieces

    A foreach loop is the easiest way to go through the array:

    foreach (string w in words) {
        Console.WriteLine(w);
    }
    

    It prints hello, world and foo, each on its own line.

    Details that matter

    Empty pieces are kept

    Two separators in a row produce an empty string between them:

    string[] a = "a,b,,c".Split(',');
    Console.WriteLine(a.Length);            // 4
    
    string[] b = "hello  world".Split(' ');
    Console.WriteLine(b.Length);            // 3
    

    The second string has two spaces, so the pieces are "hello", an empty string and "world". To drop the empty ones, pass an option:

    string[] c = "hello  world".Split(' ', StringSplitOptions.RemoveEmptyEntries);
    Console.WriteLine(c.Length);            // 2
    

    More than one separator

    You can list several separator characters, and any of them cuts the string. A separator can also be a string:

    string[] d = "a,b;c".Split(',', ';');
    Console.WriteLine(d.Length);            // 3
    
    string[] e = "a--b--c".Split("--");
    Console.WriteLine(string.Join("|", e)); // a|b|c
    

    The string.Join call glues the pieces back together with a chosen separator, which is the opposite of Split.

    Plain separators, not patterns

    The separator is plain text, not a regular expression. A . separator splits on actual dots, with no special meaning. Code ported from languages where the delimiter is a pattern sometimes escapes characters that need no escaping here.

    Limiting and trimming

    A count argument limits how many pieces you get, and StringSplitOptions.TrimEntries trims spaces from each piece:

    string[] f = "a b c d".Split(' ', 2);
    Console.WriteLine(string.Join("|", f));  // a|b c d
    
    string[] g = "a, b ,c".Split(',', StringSplitOptions.TrimEntries);
    Console.WriteLine(string.Join("|", g));  // a|b|c
    

    How many pieces to expect

    A string with k separators splits into k + 1 pieces, counting empty ones. "a,b,,c" has three commas and gives four pieces. That rule explains most surprises, including why a string that starts or ends with the separator gives an empty piece at that end:

    string[] h = " a b ".Split(' ');
    Console.WriteLine(h.Length);            // 4
    

    The pieces are an empty string, "a", "b" and another empty string.

    No separator in the string

    If the separator does not appear, the result is an array with one element, the whole string. Even an empty string gives an array of length 1, holding an empty string.

    Splitting, then converting

    Split often comes first in a small pipeline: cut the text apart, then convert each piece. This adds up numbers typed on one line:

    string line = "3 14 15";
    int sum = 0;
    
    foreach (string piece in line.Split(' ')) {
        sum += int.Parse(piece);
    }
    
    Console.WriteLine(sum);  // 32
    

    int.Parse throws a FormatException on a piece that is not a number, such as an empty string from a doubled space. That is one more reason to know about RemoveEmptyEntries.

    Calling Split() with no arguments cuts on any whitespace, so "one two".Split() returns two pieces.

    Split or Substring?

    Both cut strings apart, but they suit different jobs. Substring needs you to know the positions, so it fits fixed layouts such as "the first 6 characters". Split finds the cuts for you using a separator, so it fits text whose parts vary in length, such as words in a sentence or fields in a comma-separated line.

    The exercise, step by step

    The lesson starts with sentence set to "hello world foo".

    1. Declare a string[] named words. The result is an array of strings, so the variable needs that type.
    2. Call Split(' ') on sentence. The words are separated by single spaces, so a space character is the separator.
            string sentence = "hello world foo";
    
            string[] words = sentence.Split(' ');
    

    The array words now has three elements.

    Common mistakes

    • Mixing up the separator types. ' ' is a char and " " is a string. Both work with Split in current C#, but know which one you pass.
    • Lowercase split. The method is Split.
    • Forgetting the empty entries. Text with repeated spaces gives empty strings in the array, which can break code that expects real words.
    • Treating the result as a List. It is an array, so use Length, not Count.

    Key takeaways

    • Split returns a string[] of the pieces between separators.
    • The separator is plain text, not a regular expression.
    • Consecutive separators create empty pieces unless you use StringSplitOptions.RemoveEmptyEntries.
    • string.Join reverses a split.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free