C# LINQ: How is string(“[1, 2, 3]”) parsed as an array?

前端 未结 4 1495
谎友^
谎友^ 2020-12-17 04:40

I am trying to parse a string into array and find a very concise approach.

string line = \"[1, 2, 3]\";
string[] input = line.Substring(1, line.Length - 2).S         


        
4条回答
  •  鱼传尺愫
    2020-12-17 05:41

    The reason it does not work unless you skip the first two lines is that these lines have commas after ints. Your input looks like this:

    "1," "2," "3"
    

    Only the last entry can be parsed as an int; the initial two will produce an exception.

    Passing comma and space as separators to Split will fix the problem:

    string[] input = line
        .Substring(1, line.Length - 2)
        .Split(new[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
    

    Note the use of StringSplitOptions.RemoveEmptyEntries to remove empty strings caused by both comma and space being used between entries.

提交回复
热议问题