0
0
CsharpHow-ToBeginner · 3 min read

How to Split String in C#: Syntax and Examples

In C#, you can split a string into parts using the Split() method of the string class. This method takes one or more separator characters or strings and returns an array of substrings. For example, string.Split(',') splits a string at each comma.
📐

Syntax

The basic syntax to split a string in C# is:

string[] parts = originalString.Split(separatorChars);

Here:

  • originalString is the string you want to split.
  • separatorChars is a character or array of characters where the string will be split.
  • The method returns an array of substrings.
csharp
string[] parts = originalString.Split(',');
💻

Example

This example shows how to split a sentence into words using space as the separator.

csharp
using System;

class Program
{
    static void Main()
    {
        string sentence = "Hello world from C#";
        string[] words = sentence.Split(' ');

        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
    }
}
Output
Hello world from C#
⚠️

Common Pitfalls

Some common mistakes when using Split() include:

  • Not handling empty entries when separators are next to each other.
  • Using the wrong separator character or string.
  • Ignoring case sensitivity if splitting by strings.

To avoid empty entries, use StringSplitOptions.RemoveEmptyEntries.

csharp
using System;

class Program
{
    static void Main()
    {
        string data = "apple,,banana,,cherry";

        // Wrong: will include empty strings
        string[] parts1 = data.Split(',');
        Console.WriteLine("With empty entries:");
        foreach (var part in parts1)
            Console.WriteLine($"'{part}'");

        // Right: remove empty entries
        string[] parts2 = data.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
        Console.WriteLine("Without empty entries:");
        foreach (var part in parts2)
            Console.WriteLine($"'{part}'");
    }
}
Output
With empty entries: 'apple' '' 'banana' '' 'cherry' Without empty entries: 'apple' 'banana' 'cherry'
📊

Quick Reference

UsageDescription
string.Split(char separator)Splits string by one character separator.
string.Split(char[] separators)Splits string by multiple characters.
string.Split(char[], StringSplitOptions)Splits string and controls empty entries.
string.Split(string[], StringSplitOptions)Splits string by string separators.
StringSplitOptions.RemoveEmptyEntriesRemoves empty strings from results.

Key Takeaways

Use Split() method to divide a string into parts by separators.
Pass characters or strings as separators to control where to split.
Use StringSplitOptions.RemoveEmptyEntries to avoid empty results.
The method returns an array of substrings you can loop through.
Always check your separators match the string content to split correctly.