繁体   English   中英

如何使用字符串分隔符拆分字符串?

[英]How can I split a string using a string delimeter?

如何使用字符串分隔符拆分字符串?

我试过了:

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

我收到错误:

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

在给定的字符串参数上拆分字符串的推荐方法是什么?

有一个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);
}

这不是你要搜索的超载吗? http://msdn.microsoft.com/en-us/library/1bwe3zdy.aspx

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

写一个扩展方法:

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

问题解决了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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