How to Split String by String in C#
Strings
are the object used to store textual data. The C# System.String
library provides numerous methods for manipulating, creating, and comparing strings.
One common situation we often come across is splitting a string to extract some important data. This article will focus on splitting a string using another string and different ways of performing this operation in C#.
Using the String.Split()
Method in C#
The String.Split()
method has different overloads providing us with different methods of splitting a string
.
We are interested in one particular overload which takes a string
as an argument and uses it as a delimiter to split the given string
into its substrings.
using System;
public class Example {
public static void Main() {
string str = "Delft@@Stack";
string separator = "@@";
string[] tokens = str.Split(new string[] { separator }, StringSplitOptions.None);
Console.WriteLine(String.Join(" ", tokens));
}
}
Output:
Delft Stack
In the above method, we split the given string using the delimiter string @@
into an array of substrings and then print by concatenating them with a space.
Using the Regex.Split()
Method in C#
The Regex.Split()
method does what we want to achieve. It takes the input string and splits it into an array of substrings based on the regex condition match.
using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
string str = "Delft@@Stack";
string separator = "@@";
string[] tokens = Regex.Split(str, separator);
Console.WriteLine(String.Join(" ", tokens));
}
}
Output:
Delft Stack
As from the code sample above, the Regex.Split()
method has an even simpler usage than the String.Split()
method. It is even faster and more efficient in execution.
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedIn