How to split a string using string delimiter in C#
When dealing with complex strings, it is often necessary to split them into smaller components. While the .Split() method in C# works with single character delimiters, it can be tricky when you need to split by string delimiters.
Let us consider the following example string:
<code>"My name is Marco and I'm from Italy"</code>
To split this string by the delimiter "is Marco and" you can use:
<code>string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);</code>
In this code, we pass an array containing the delimiter string as the first parameter. The StringSplitOptions.None parameter ensures that the separator is treated as a single string rather than multiple single characters.
As a result, the tokens array will contain two elements:
If the separator is a single character, a simpler code form can be used:
<code>string[] tokens = str.Split(',');</code>
This will split the string by comma characters.
The above is the detailed content of How to Split a String Using a String Delimiter in C#?. For more information, please follow other related articles on the PHP Chinese website!