Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string using a string delimeter?

How can I split a string using a string delimeter?

I've tried:

string[] htmlItems = correctHtml.Split("<tr");

I get the error:

Cannot convert from 'string' to 'char[]'

What's the recommended way to split a string on a given string parameter?

like image 625
Only Bolivian Here Avatar asked Apr 24 '26 19:04

Only Bolivian Here


2 Answers

There is a version of string.Split that takes a string array and an options parameter:

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] {"[stop]"};
string[] result = source.Split(stringSeparators, StringSplitOptions.None);

so even though you only have one separator you want to split on you still have to pass it as an array.

Taking Mike Hofer's answer as a starting point, this extension method will make it a bit simpler to use.

public static string[] Split(this string value, string separator)
{
    return value.Split(new string[] {separator}, StringSplitOptions.None);
}
like image 178
ChrisF Avatar answered Apr 27 '26 07:04

ChrisF


Have a look at Regex.Split

http://msdn.microsoft.com/en-us/library/aa332139(v=vs.71).aspx

like image 43
Pleun Avatar answered Apr 27 '26 08:04

Pleun