如何使用字符串分隔符分割字符串?如何使用字符串分隔符分割字符串?
我已經試過:
string[] htmlItems = correctHtml.Split("<tr");
我得到的錯誤:
Cannot convert from 'string' to 'char[]'
什麼是拆就一個給定的字符串參數字符串的推薦的方法?
如何使用字符串分隔符分割字符串?如何使用字符串分隔符分割字符串?
我已經試過:
string[] htmlItems = correctHtml.Split("<tr");
我得到的錯誤:
Cannot convert from 'string' to 'char[]'
什麼是拆就一個給定的字符串參數字符串的推薦的方法?
有和string.Split
一個版本,需要一個字符串數組的選項參數:
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);
}
打了我22秒+1 ... – 2011-05-11 21:14:29
謝謝,這工作很好,雖然代碼有點複雜。 :) – 2011-05-11 21:16:10
您還需要使用StringSplitOptions參數在斯普利特。
這不是你正在尋找的重載嗎? http://msdn.microsoft.com/en-us/library/1bwe3zdy.aspx
收件擴展方法:
public static string[] Split(this string value, string separator)
{
return value.Split(separator.ToCharArray());
}
問題解決了。
好主意,雖然此實現將失敗,因爲分隔符比單個字符長。 – ChrisF 2011-05-11 21:54:41
我沒有看到任何將字符串作爲唯一參數的重載。我錯過了什麼嗎? http://msdn.microsoft.com/en-us/library/system.string.split.aspx – ChaosPandion 2011-05-11 21:12:43
@ChaosPandion:問題是我將如何拆分給定單詞的字符串。 – 2011-05-11 21:14:07