[英]Cannot implicitly convert string[] to string when splitting
I am new to c# and I don't understand why this isn't working.我是 c# 新手,我不明白为什么这不起作用。 I want to split a previously splitted string.我想拆分以前拆分的字符串。
My code is the following:我的代码如下:
int i;
string s;
string[] temp, temp2;
Console.WriteLine("write 'a-a,b-b,c-c,d-d'";
s = Console.ReadLine();
temp = s.Split(',');
for (i = 0; i < temp.Length; i++)
temp2[i] = temp[i].Split('-');
I get the following error Cannot implicitly convert type 'string[]' to 'string
我收到以下错误Cannot implicitly convert type 'string[]' to 'string
I want to end with:我想以:
temp = {a-a , b-b , c-c , d-d};
temp2 = {{a,a},{b,b},{c,c},{d,d}};
The result of string.Split()
is string[]
, which you should already see by the correct usage when you assign to string[] temp
. string.Split()
的结果是string[]
,当您分配给string[] temp
时,您应该已经通过正确的用法看到了它。 But when you are assigning to the elements of string[] temp2
, you are trying to store arrays of strings in slots that are meant to only store strings , hence the compiler error.但是,当您分配给string[] temp2
的元素时,您试图将字符串数组存储在仅用于存储strings 的插槽中,因此会出现编译器错误。 Your code could work with a simple change below.您的代码可以在下面进行简单的更改。
string[] temp;
string[][] temp2; // array of arrays
string s = "a-a,b-b,c-c,d-d";
temp = s.Split(',');
temp2 = new string[temp.Length][];
for (int i = 0; i < temp.Length; i++)
temp2[i] = temp[i].Split('-');
When you call split, it returns an array of strings.当您调用 split 时,它返回一个字符串数组。 You can't assign string[] to a string variable.您不能将 string[] 分配给字符串变量。
As others have said, Split
returns an array.正如其他人所说, Split
返回一个数组。 However, you can split on more than one character at a time.但是,您可以一次拆分多个字符。 For example,例如,
string s = "a,b,c,d-d";
var split = s.Split(new[] {',', '-'});
In this case, the split
array would contain 5 indices, containing "a", "b", "c", "d", and "d".在这种情况下, split
数组将包含 5 个索引,包括“a”、“b”、“c”、“d”和“d”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.