C# string Join and Split

In this source code example, we will see how to join and split strings in C# with an example.

The Join method joins strings and the Split method splits the strings.

C# string Join and Split


using System;

class Example {
    static void Main() {
        
        var items = new string[] { "C#", "Visual Basic", "Java", "Perl" };

        var langs = string.Join(",", items);
        Console.WriteLine(langs);
        
        string[] langs2 = langs.Split(',');
        
        foreach (string lang in langs2)
        {
            Console.WriteLine(lang);
        }
    }
}

Output:

C#,Visual Basic,Java,Perl

C#

Visual Basic

Java

Perl
All words from the array are joined. We build one string from them. There will be a comma character between every two words.
        var items = new string[] { "C#", "Visual Basic", "Java", "Perl" };

        var langs = string.Join(",", items);
As a reverse operation, we split the langs string. The Split method returns an array of words, delimited by a character. In our case, it is a comma character:
        string[] langs2 = langs.Split(',');
We go through the array and print its elements:
        foreach (string lang in langs2)
        {
            Console.WriteLine(lang);
        }


Comments