How to Split a String in C#

Splitting a string in C# can be done using the Split method available in the String class. This method allows you to separate a string into substrings based on a specified delimiter. Here’s an example of how to use the Split method:

using System;

class Program
{
    static void Main()
    {
        string originalString = "Hello,World,How,Are,You";

        // Split the string using a comma as the delimiter
        string[] substrings = originalString.Split(',');

        // Display the substrings
        foreach (var substring in substrings)
        {
            Console.WriteLine(substring);
        }
    }
}

In this example, we start by including the System namespace, which contains the String class. We then define the originalString and use the Split method to separate it into substrings based on the comma delimiter. Finally, we iterate through the resulting substrings and print them to the console.

The output of the above code will be:

Hello
World
How
Are
You

You can customize the delimiter and use different overloads of the Split method to achieve more complex splitting operations.

Splitting strings is a common task in C# and understanding how to use the Split method effectively can greatly enhance your string manipulation capabilities.

Leave a comment