C# string.Split returns double quotes out of no where
Why does this
string test = "Text1, Text2";
string [] tests = test.Split(", "开发者_如何学C.ToArray());
returns this
[0] = "Text1"
[1] = ""
[2] = "Text2"
what's with the quotes in tests[1] ?
I thought the output would be like this
[0] = "Text1"
[1] = "Text2"
It's a LINQ extension method that is causing you grief!
You'll find that System.String
implements IEnumerable<char>
which allows strings to use any of the LINQ extension methods - and you are calling TSource[] ToArray<TSource>(this IEnumerable<TSource> source)
. So instead of splitting on an array of strings, you are splitting on an array of characters.
Your code can be rewritten as:
string test = "Text1, Text2";
char[] separator = ", ".ToArray();
string[] tests = test.Split(separator);
Since your input contains two of the separator characters next to each other you get the empty string in your output array.
There isn't a Split
method on System.String
that takes a single string as the separator. Instead you must pass in an array of string separators. The method also requires that you provide the StringSplitOptions
parameter.
So this is what you need to call:
string test = "Text1, Text2";
string[] separator = new [] { ", " };
string[] tests = test.Split(separator, StringSplitOptions.RemoveEmptyEntries);
string [] tests = test.Split(new string[] { ", " });
What about this?
String.ToArray()
splits the string into the chars array, but you need an array of strings as an argument of String.Split()
.
", ".ToArray()
results an character array like:
{ ',', ' '} //a ',' and a space
so there are TWO separators (matches the string.Split(params char[])
version).
You should do it like this:
string test = "Text1, Text2";
string[] tests = test.Split(new string[] { ", " },
StringSplitOptions.RemoveEmptyEntries);
// Updated
or
string test = "Text1, Text2";
string[] tests = test.Split(',');
// or: string[] tests = test.Split(new char[]{ ',' });
Your code
string test = "Text1, Text2";
string [] tests = test.Split(", ".ToArray());
equals to
string test = "Text1, Text2";
string [] tests = test.Split(new char[2]{',',' '});
You should use
string test = "Text1, Text2";
string [] tests = test.Split(',');
Change ToArray() to ToCharArray().
精彩评论