Cannot implicitly convert string[] to string when splitting

前端 未结 3 2055
悲哀的现实
悲哀的现实 2020-12-21 20:25

I am new to c# and I don\'t understand why this isn\'t working. I want to split a previously splitted string.

My code is the following:

int i;
string         


        
相关标签:
3条回答
  • 2020-12-21 21:18

    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('-'); 
    
    0 讨论(0)
  • 2020-12-21 21:26

    As others have said, Split returns an array. 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".

    0 讨论(0)
  • 2020-12-21 21:27

    When you call split, it returns an array of strings. You can't assign string[] to a string variable.

    0 讨论(0)
提交回复
热议问题