views:

266

answers:

2

I would like to split a string into a String[] using a String as a delimiter.

String delimit = "[break]";
String[] tokens = myString.Split(delimit);

But the method above only works with a char as a delimiter.

Any takers?

+15  A: 

Like this:

mystring.Split(new string[] { delimit }, StringSplitOptions.None);

For some reason, the only overloads of Split that take a string take it as an array, along with a StringSplitOptions.
I have no idea why there isn't a string.Split(string) overload.

SLaks
Great answer. Worked first time. =)
Kieran
+4  A: 

I personally prefer to use something like this, since regex has that split:

public static string[] Split(this string input, string delimit)
{
  return Regex.Split(input, delimit);
}
Victor
+1 to be on the safe side I suggest using `Regex.Escape(delimit)` to escape any metacharacters that might be part of the delimiter.
Ahmad Mageed
Since the string isn't really a regex, there's no point in invoking the regex parser.
SLaks
`Regex.Split` parses the input first, which is expensive, and then splits the output of the **matches**
Munim Abdul
@Munim True, Regex is working with matching groups, but OP is asking about "easy" way, not "fastest" way. Seems easy enough for me.
Victor
I agree with you @Victor. This is the easiest but the slowest :) Cheers
Munim Abdul