OneBite.Dev - Coding blog in a bite size

Split A String By A Delimiter In C#

Code snippet for how to Split A String By A Delimiter In C# with sample and detail explanation

Splitting a string by a delimiter is a common programming requirement and C# provides built-in methods to handle it efficiently. In this article, we will explore how to use the ‘Split’ method in C# to divide a string by a given delimiter.

Code snippet: Using the Split method in C#

string str = "Hello, World!";
char[] delimiter = new char[] { ',' };
string[] splitStr = str.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in splitStr)
{
  Console.WriteLine(s);
}

Code Explanation: Using the Split method in C#

The code snippet given above demonstrates how to split a string by a delimiter using C#. Here’s a step by step explanation;

  1. First, we define a string to be divided:

    string str = "Hello, World!";

    This creates a string named ‘str’ with the text “Hello, World!“.

  2. Next, we define the delimiter as a character array:

     char[] delimiter = new char[] { ',' };

    We create a ‘delimiter’ variable and set it to a character array that includes our delimiter (comma in this case).

  3. We then use the ‘Split’ method to divide the string:

     string[] splitStr = str.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);

    The ‘Split’ method from the ‘str’ string object breaks up the string into an array of strings. It uses the ‘delimiter’ character as the point at which to split the string. The ‘StringSplitOptions.RemoveEmptyEntries’ option ensures that no empty strings are returned in the result.

  4. Finally, we use a ‘foreach’ loop to print each divided string:

     foreach (string s in splitStr)
     {
       Console.WriteLine(s);
     }

    This loop iterates over each element (s) in the ‘splitStr’ string array and prints it to the console.

When you run this code, it will print:

Hello
 World!

So, as you can see the initial string has been split into two separate strings at the point of the delimiter. Remember that whitespace is also considered a part of the string while splitting.

c-sharp