Home >Backend Development >C++ >How to Split a String in C# Using a Multi-Character Delimiter like ']['?

How to Split a String in C# Using a Multi-Character Delimiter like ']['?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 04:40:41680browse

How to Split a String in C# Using a Multi-Character Delimiter like

String Splitting with Multiple Character Delimiters

Question: How can I split a string in C# using a delimiter of "]["?

Consider the string "abc]rfd[,][.". The desired output is an array containing "abc", "rfd", "5", "," and ".".

Answer:

There are two approaches to splitting a string with multiple character delimiters:

Using string.Split and an Array of Delimiters

The string.Split method allows you to pass an array of delimiters to split the string. To split on "][", use the following code:

string Delimiter = "][";
var Result = StringToSplit.Split(new[] { Delimiter }, StringSplitOptions.None);

Using Regular Expressions with Regex.Split

You can also use a regular expression to split the string. In this case, the delimiter "][" is represented as "][":

string input = "abc][rfd][5][,][.";
string[] parts2 = Regex.Split(input, @"\]\[");

Both methods will produce the desired array of strings:

["abc", "rfd", "5", ",", "."]

The above is the detailed content of How to Split a String in C# Using a Multi-Character Delimiter like ']['?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn