Home >Backend Development >C++ >How Can I Split Strings by Multi-Character Delimiters in C#?
Split string using multi-character delimiter in C#
Splitting a string using delimiters is a common task in programming. But what if the required separator consists of multiple characters (e.g. a word)?
Comparison of Java and C#
In Java, use the String.split() method to directly split a string using the string delimiter:
<code class="language-java">String sentence = "This is a sentence."; String[] split = sentence.split("is");</code>
However, in C#, the String.Split() method only accepts single-character delimiters.
Solution using StringSplitOptions
To split a string using multi-character delimiter in C#, you can use the StringSplitOptions.None enumeration value and the String.Split() method:
<code class="language-csharp">string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"; string[] stringSeparators = new string[] {"[stop]"}; string[] result; // ... result = source.Split(stringSeparators, StringSplitOptions.None); foreach (string s in result) { Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "" : s); }</code>
In this example, source
contains a string in which the string "[stop]" appears multiple times as a delimiter. The code uses String.Split()
to split the string into an array of substrings. The StringSplitOptions.None
value ensures that the delimiter string is treated as a single delimiter, even if it contains multiple characters.
With this technique you can easily split strings using multi-character delimiters in C#. The output will be words separated by "[stop]".
The above is the detailed content of How Can I Split Strings by Multi-Character Delimiters in C#?. For more information, please follow other related articles on the PHP Chinese website!