Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to split a string with a string delimiter in C#?
String splitting in C# is a common operation used to divide a string into substrings based on specified delimiters. The Split() method provides multiple overloads to handle different types of delimiters including characters, strings, and arrays.
Syntax
Following are the common syntax forms for splitting strings −
// Split by single character
string[] result = str.Split(',');
// Split by character array
char[] delimiters = {',', ';', '|'};
string[] result = str.Split(delimiters);
// Split by string delimiter
string[] result = str.Split(new string[] {"||"}, StringSplitOptions.None);
Using Character Delimiters
The simplest way to split a string is using a single character delimiter −
using System;
class Program {
static void Main() {
string str = "Welcome,to,New York";
string[] arr = str.Split(',');
foreach (string val in arr) {
Console.WriteLine(val);
}
}
}
The output of the above code is −
Welcome to New York
Using String Delimiters
To split using string delimiters (multiple characters), use the string array overload −
using System;
class Program {
static void Main() {
string str = "apple||banana||cherry||date";
string[] delimiters = new string[] {"||"};
string[] arr = str.Split(delimiters, StringSplitOptions.None);
foreach (string val in arr) {
Console.WriteLine(val);
}
}
}
The output of the above code is −
apple banana cherry date
Using Multiple Delimiters
You can split a string using multiple different delimiters simultaneously −
using System;
class Program {
static void Main() {
string str = "apple,banana;cherry|date:grape";
char[] delimiters = new char[] {',', ';', '|', ':'};
string[] arr = str.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
foreach (string val in arr) {
Console.WriteLine(val);
}
}
}
The output of the above code is −
apple banana cherry date grape
StringSplitOptions
The StringSplitOptions enumeration controls how empty entries are handled −
| Option | Description |
|---|---|
| None | Includes empty strings in the result array |
| RemoveEmptyEntries | Excludes empty strings from the result array |
Example with Empty Entries
using System;
class Program {
static void Main() {
string str = "apple,,cherry,";
Console.WriteLine("With None option:");
string[] arr1 = str.Split(',');
for (int i = 0; i
The output of the above code is −
With None option:
[0]: 'apple'
[1]: ''
[2]: 'cherry'
[3]: ''
With RemoveEmptyEntries option:
[0]: 'apple'
[1]: 'cherry'
Conclusion
The Split()StringSplitOptions.RemoveEmptyEntries to exclude empty results when dealing with consecutive delimiters or trailing separators.
