OneBite.Dev - Coding blog in a bite size

Convert A String To An Array In C#

Code snippet for how to Convert A String To An Array In C# with sample and detail explanation

In programming, there might be scenarios where we need to convert a string into an array to work with individual elements more conveniently. In C#, this conversion is facilitated using inbuilt string functions.

Code Snippet: Converting String to Array in C#

Consider this code snippet highlighting how to convert a string into an array in C#.

string str = "Hello, World!";
string[] strArray = str.Split(',');

foreach(var word in strArray)
{
    Console.WriteLine(word);
}

Code Explanation: Converting String to Array in C#

In this code sequence, we are going to explain step by step how a string is converted into an array in C#.

The first line string str = "Hello, World!"; is simply initialising a string named str with a pair of words separated by a comma.

In the next line string[] strArray = str.Split(',');, the str.Split(',') function is being utilized. This function divides the original string each time it sees the character provided as a parameter, which is a comma in our example. For each divide, it stores the individual chunk as an element in an array. Here, our array strArray will store two elements: “Hello” and ” World!“.

Finally, there is a foreach loop that prints each word (array element) to the console. In this loop, var word will first be “Hello”, since that is the first element in our string array, and then it will be ” World!”, which is the second element in the array. This loop will continue until there are no more elements in the array.

This method of converting a string into an array can be particularly useful in situations where we need to manipulate individual phrases, characters, or groups of characters within a single string. C#‘s inbuilt string functions make this conversion quite straightforward.

c-sharp