简体   繁体   English

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

[英]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.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);

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. 以Mike Hofer的答案为出发点,这种扩展方法将使其更简单易用。

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 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. 问题解决了。

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

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