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:
-
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. -
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. -
The
Main
method is the entry point of a C# program, where our code starts execution. -
Inside the
Main
method, we first declare a strings
with the value “Apple,Banana,Cherry”. This is the string that we want to split by the comma sign. -
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 strings
by ’,’ (comma). The result of the operation is stored in the arraywords
. -
Next, we use a
foreach
loop to iterate over each element (sub-string) of the ‘words’ array. Note that the variableword
will hold the current sub-string on each iteration. -
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#.