In this article, we will provide the method of splitting a string into an array of string elements.
How to Split a String into String Array Elements in C#?
The “Split()” function in C# is used to split a string into the components of a string array, which is a common operation that is included in the “System”. Users can divide a string of characters into an array of substrings using the “String class” and a designated delimiter.
Syntax
The general syntax of the “Split()” method in C# is stated below:
As you can see, the above-stated method takes one parameter, such as “char[]”.
Follow the provided instructions to understand the procedure of splitting the string into the elements of an array string:
At first, declare a string variable and then assign it some value:
Next, pass the delimiter as an argument to the “Split()” function. Here, we have specified a comma as the delimiter in this instance. Then, pass it to the string array variable:
After that, use the array index to access the elements of the string:
Console.WriteLine(my_Array[1]); // Output: is
Console.WriteLine(my_Array[2]); // Output: Monday
Example: Split() Function to Split Elements of String Array
Users can pass in an array of characters to serve as the delimiter as a parameter if they need to divide a text into an array according to delimiters. For that specific purpose, check out the provided illustration:
class Split {
static void Main() {
Console.WriteLine("Separated strings according to comma");
// String of days_Names
string days_Names = "Monday, Tuesday, Wednesday, Thursday, Friday, Saturday Sunday";
// Split days_Names separated by a comma followed by space as referred to array indexes
string[] days_NamesList = days_Names.Split(", ");
foreach (string days_Name in days_NamesList)
Console.WriteLine(days_Name);//print the days_Names
}
}
In the above instance, the delimiters are represented by the comma sign. Based on these delimiters, the “Split()” function divides the text into six components. It divides the string into substrings according to the elements(characters) of an array.
According to the below output, the provided input string has been divided into substrings:
That’s all! We have compiled the easiest way to split a string into elements of a string-type array in C#.
Conclusion
In C#, the operation of separating an array of strings into elements of an array of strings, the “Split()” function can be used. A string can be divided into an array of substrings that are accessible by their index by defining a delimiter. That’s all about this tutorial.