如何使用字符串分隔符拆分字符串?我尝试过:
string[] htmlItems = correctHtml.Split("<tr");
我收到错误:
Cannot convert from 'string' to 'char[]'
在给定的字符串参数上拆分字符串的推荐方法是什么?
答案 0 :(得分:7)
有一个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);
所以,即使您只想要拆分一个分隔符,仍然必须将其作为数组传递。
以Mike Hofer的答案为出发点,这种扩展方法可以使它更简单易用。
public static string[] Split(this string value, string separator)
{
return value.Split(new string[] {separator}, StringSplitOptions.None);
}
答案 1 :(得分:1)
答案 2 :(得分:1)
答案 3 :(得分:0)
您还需要在Split中使用StringSplitOptions参数。
答案 4 :(得分:0)
编写扩展方法:
public static string[] Split(this string value, string separator)
{
return value.Split(separator.ToCharArray());
}
问题解决了。