简体   繁体   中英

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?

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);
}

Isn't this the overload you are searching for? http://msdn.microsoft.com/en-us/library/1bwe3zdy.aspx

您还需要在Split中使用StringSplitOptions参数。

Write an extension method:

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

Problem solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM