C# – Split String with Character as Delimiter

To split a String with specific character as delimiter in C#, call Split() on the string instance and pass the delimiter character as argument to this method. The method returns a String array with the splits.

Reference to C# String.Split() method.

Examples

ADVERTISEMENT

1. Split string with hyphen ‘-‘ as delimiter

In the following program, we will take a string ab-cd-efg and split this string with '-' as delimiter using String.Split(Char) method.

C# Program

using System;
  
class Example {
    static void Main(string[] args) {
        String str = "ab-cd-efg";
        Char delimiter = '-';
        String[] result = str.Split(delimiter);
        for (int i = 0; i < result.Length; i++) {
            Console.WriteLine(result[i]);
        }
    }
}

Output

ab
cd
efg

2. Split string with comma ‘,’ as delimiter

In the following program, we will take a comma separated string ab,cd,efg and split this string with ',' as delimiter using String.Split(Char) method.

C# Program

using System;
  
class Example {
    static void Main(string[] args) {
        String str = "ab,cd,efg";
        Char delimiter = ',';
        String[] result = str.Split(delimiter);
        for (int i = 0; i < result.Length; i++) {
            Console.WriteLine(result[i]);
        }
    }
}

Output

ab
cd
efg

Conclusion

In this C# Tutorial, we have learned how to split a given string with a specified delimiter character, using String.Split() method.