In C#, we can use String .Split() method, which splits a string into an array of strings, so in this article, I have mentioned few possible ways to use String.Split() method and how we can split string into an array with console application example.
.Split()
Method delimiters can be a character or an array of characters or an array of strings. There are around 10 Overloads for String.Split() method. Commonly used are:
Split(Char[])
: Splits a string into substrings based on specified delimiting characters.Split(Char, StringSplitOptions)
: Splits a string into substrings based on a specified delimiting character and, optionsSplit(Char[], Int32)
: First Argument specifies, delimiting character and second one specifies maximum number of substrings.Split(String, StringSplitOptions)
: Splits a string into substrings that are based on the provided string separator.Split(Char[], StringSplitOptions)
: Splits a string into substrings based on specified delimiting characters and options.Split(String[], StringSplitOptions)
: Splits a string into substrings based on the strings in an array.
Split String Into an Array by Comma
Let's a look at an console application example, in which we will split string into array using comma as a delimiter in C#
using System;
namespace StringSplitArray
{
public class Program
{
static void Main(string[] args)
{
var names = "Vikram,Vikas,Vinod,Hitesh,Prem";
//split names string into array
string[] namesList = names.Split(",");
//loop and print
foreach (string name in namesList)
{
Console.WriteLine(name);
}
}
}
}
Output:
Vikram
Vikas
Vinod
Hitesh
Prem
Split String By Word
You can also pass a sub-string as an argument to split a string in C# using Split()
Method, here is an example of using it in C#
var str = "Hello This World";
//split by word
string[] words = str.Split("This");
//loop and print
foreach (string name in words)
{
Console.WriteLine(name);
}
Output:
Hello
World
Split String by Multiple delimiters
As mentioned above in Split() Overloads, we can pass multiple characters also to split a single string.
Here is an example of using it
var names = "Vikram,Vikas;Vinod Hitesh;Prem,Pooja";
//split names string into array
string[] namesList = names.Split(new char[] {',',' ',';'});
//loop and print
foreach (string name in namesList)
{
Console.WriteLine(name);
}
Output:
Vikram
Vikas
Vinod
Hitesh
Prem
Pooja
I hope this article clears the concept related to C# Split().
You may also like to read:
Switch case multiple conditions in C#
How to define C# multiline string literal?
Int to Enum or Enum to Int in C#
Create a calculator in C# console application
How to add Double quotes in String in C#?
Extract String after a character or before character in SQL Server