分割时无法将string []隐式转换为字符串 [英] Cannot implicitly convert string[] to string when splitting
问题描述
我是C#的新手,我不明白为什么这不起作用.我想分割一个先前分割的字符串.
I am new to c# and I don't understand why this isn't working. I want to split a previously splitted string.
我的代码如下:
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('-');
出现以下错误无法将类型'string []'隐式转换为'string
我想结束:
temp = {a-a , b-b , c-c , d-d};
temp2 = {{a,a},{b,b},{c,c},{d,d}};
推荐答案
string.Split()
的结果是 string []
,您应该已经看到分配给 string [] temp
时的正确用法.但是,当您分配给 string [] temp2
的元素时,您试图将字符串数组存储在本应仅存储 strings 的插槽中em>,因此出现编译器错误.您的代码可以通过下面的一个简单更改进行工作.
The result of string.Split()
is string[]
, which you should already see by the correct usage when you assign to 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. 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('-');
这篇关于分割时无法将string []隐式转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!