Use multi-character delimiter to split string in C#
When splitting a string using the Split
method in C#, the default behavior is to use a single character delimiter. However, in some cases you may need to use a delimiter that consists of multiple characters, such as a word.
To do this, you can specify a delimiter string when calling the Split
method. The following example demonstrates how to split the string "This is a sentence" using the delimiter "is":
<code class="language-csharp">string source = "This is a sentence"; string[] stringSeparators = new string[] { "is" }; string[] result = source.Split(stringSeparators, StringSplitOptions.None); foreach (string s in result) { Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "" : s); }</code>
This code will produce the following output:
<code>'This ' 'a sentence' ' '</code>
StringSplitOptions.None
argument indicates that the split should not remove empty elements from the resulting array. If you want to remove empty elements, you can specify StringSplitOptions.RemoveEmptyEntries
instead.
Further reading:
The above is the detailed content of How to Split Strings with Multi-Character Delimiters in C#?. For more information, please follow other related articles on the PHP Chinese website!