How can I split a string using a string delimiter?

How to split a string using string separator?

I tried:

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

I get an error message:

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

What is the recommended way to split a string into a given string parameter?

+3
source share
5 answers

There is a version string.Splitthat accepts a string array and the 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);

therefore, although you only have one separator that you want to split, you still need to pass it as an array.

Taking Mike Hofer as a starting point, this extension method will make it easier to use.

public static string[] Split(this string value, string separator)
{
    return value.Split(new string[] {separator}, StringSplitOptions.None);
}
+7
source

StringSplitOptions Split.

0

:

public static string[] Split(this string value, string separator)
{
    return value.Split(separator.ToCharArray());
}

.

0
source

All Articles