string test = "Text1, Text2";
string [] tests = test.Split(", ".ToArray());
返回此
[0] = "Text1"
[1] = ""
[2] = "Text2"
什麼用引號是在測試中[1]?
我想輸出會是這樣
[0] = "Text1"
[1] = "Text2"
string test = "Text1, Text2";
string [] tests = test.Split(", ".ToArray());
返回此
[0] = "Text1"
[1] = ""
[2] = "Text2"
什麼用引號是在測試中[1]?
我想輸出會是這樣
[0] = "Text1"
[1] = "Text2"
這是一個LINQ擴展方法,是造成你節哀!
你會發現System.String
implements IEnumerable<char>
它允許字符串使用任何LINQ擴展方法 - 並且你打電話TSource[] ToArray<TSource>(this IEnumerable<TSource> source)
。因此,不是在字符串數組上進行分割,而是在字符數組上進行分割。
您的代碼可以被改寫爲:
string test = "Text1, Text2";
char[] separator = ", ".ToArray();
string[] tests = test.Split(separator);
因爲你的輸入包含兩個分隔符的旁邊對方你在你的輸出數組空字符串。
System.String
上沒有Split
方法,它將單個字符串作爲分隔符。相反,您必須傳入一個字符串分隔符數組。該方法還要求您提供StringSplitOptions
參數。
所以這是你需要所說:
string test = "Text1, Text2";
string[] separator = new [] { ", " };
string[] tests = test.Split(separator, StringSplitOptions.RemoveEmptyEntries);
感謝您的完整解釋和解答 – lKashef 2010-12-16 15:59:03
string [] tests = test.Split(new string[] { ", " });
這個
什麼?
String.ToArray()
將字符串拆分爲字符數組,但您需要一個字符串數組作爲參數String.Split()
。
如果您將此StringSplitOptions.RemoveEmptyEntries添加到Split方法參數中,那麼這將起作用,因爲只接受字符串數組的唯一重載也會使用StringSplitOptions對象。 – lKashef 2010-12-16 15:33:59
您的代碼
string test = "Text1, Text2";
string [] tests = test.Split(", ".ToArray());
等於
string test = "Text1, Text2";
string [] tests = test.Split(new char[2]{',',' '});
您應該使用
string test = "Text1, Text2";
string [] tests = test.Split(',');
", ".ToArray()
結果的字符數組,如:
{ ',', ' '} //a ',' and a space
所以有兩個分隔符(匹配string.Split(params char[])
版本)。
你應該做的是這樣的:
string test = "Text1, Text2";
string[] tests = test.Split(new string[] { ", " },
StringSplitOptions.RemoveEmptyEntries);
// Updated
或
string test = "Text1, Text2";
string[] tests = test.Split(',');
// or: string[] tests = test.Split(new char[]{ ',' });
+ +1爲簡單的解釋,但請編輯您的答案,因爲第一個解決方案將作爲字符串提供編譯錯誤.Split不會接受字符串作爲參數,但如果您將「,」放在字符串數組中它將工作.....第二個解決方案正在工作,但它會導致不必要的空間,因爲分隔符是「,」不是「,」感謝您的幫助=) – lKashef 2010-12-16 15:41:31
變化ToArray的()來ToCharArray()。
爲什麼您將.ToArray()添加到「,」? – Anton 2010-12-16 06:45:53
測試[1]中的引號是什麼?所有三個值都有引號。只是測試[1]沒有別的,因爲它是空的。使用StringSplitOptions.RemoveEmptyEntries刪除空值。 – 2010-12-16 06:53:54