簡體   English   中英

C#string.Split返回雙引號

[英]C# string.Split returns double quotes out of no where

為什么這樣

        string test = "Text1, Text2";
        string [] tests = test.Split(", ".ToArray());

返回這個

[0] = "Text1"
[1] = ""
[2] = "Text2"

測試[1]中的引號是什么?

我以為輸出是這樣的

[0] = "Text1"
[1] = "Text2"

這是一種LINQ擴展方法 ,使您感到悲傷!

您會發現System.String實現了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);
string [] tests = test.Split(new string[] { ", " });

那這個呢?

String.ToArray()將字符串拆分為chars數組,但是您需要一個字符串數組作為String.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[]{ ',' });

將ToArray()更改為ToCharArray()。

您的密碼

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(',');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM