Onl*_*ere 3 c# string split .net-4.0
如何使用字符串分隔符拆分字符串?
我试过了:
string[] htmlItems = correctHtml.Split("<tr");
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Cannot convert from 'string' to 'char[]'
Run Code Online (Sandbox Code Playgroud)
在给定的字符串参数上拆分字符串的推荐方法是什么?
有一个版本string.Split需要一个字符串数组和一个options参数:
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);
Run Code Online (Sandbox Code Playgroud)
因此,即使您只想要拆分一个分隔符,仍然必须将其作为数组传递.
以Mike Hofer的答案为出发点,这种扩展方法将使其更简单易用.
public static string[] Split(this string value, string separator)
{
return value.Split(new string[] {separator}, StringSplitOptions.None);
}
Run Code Online (Sandbox Code Playgroud)