OneBite.Dev - Coding blog in a bite size

Split A String By Comma Sign In C#

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

Splitting a string by a specific character or sequence is a fundamental operation in programming. In C#, this can be done using various methods, but in this article, we will be exploring how to split a string by a comma sign.

Code Snippet: Split A String By Comma Sign In C#

Below is a simple C# code snippet that splits a string by a comma sign.

using System;

class Program
{
    static void Main()
    {
        string s = "Apple,Banana,Cherry";
        string[] words = s.Split(',');

        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
    }
}

When you run this code, it will output:

Apple
Banana
Cherry

Code Explanation for Split A String By Comma Sign In C#

Let’s break down this code to understand it better:

  1. First, we are using the System namespace to allow us to write to the Console. Every C# program needs to use the using System; directive.

  2. The Program class is declared, which is the basic unit of a C# program. Every C# program has at least one class that contains the Main method.

  3. The Main method is the entry point of a C# program, where our code starts execution.

  4. Inside the Main method, we first declare a string s with the value “Apple,Banana,Cherry”. This is the string that we want to split by the comma sign.

  5. The Split method in C# is used to split a string into an array of substrings based on the characters in an array. In this case, we are splitting the string s by ’,’ (comma). The result of the operation is stored in the array words.

  6. Next, we use a foreach loop to iterate over each element (sub-string) of the ‘words’ array. Note that the variable word will hold the current sub-string on each iteration.

  7. Inside the loop, we print out each word using the Console.WriteLine(word); statement.

That’s it! With these simple steps, you can easily split a string by a comma sign in C#.

c-sharp