C# parsing a text file and storing the values in an array

前端 未结 3 2086
北恋
北恋 2021-01-23 13:58

I am trying to read in a text file which has this format below, into an array:

Previous errors were for Test id \'1234567\' Error id \'12345678\'
Previous errors         


        
3条回答
  •  旧巷少年郎
    2021-01-23 14:16

    Since you already have an array with all the lines of text in, you could just iterate over them, and read out the numbers from each.

    One such solution:

    // Extention method to simplify:
    public static string GetNumbersFromPos(this string line, int nrToSkip)
    {
        return new string(line.Skip(nrToSkip)
                                .TakeWhile(c => Char.IsNumber(c))
                                .ToArray());
    }
    
    // Assume you get this from your array:
    var eachLine = "Previous errors were for Test id '1234567' Error id '12345678'";
    
    // Find nr of chars to skip
    var beforeFirstId = eachLine.IndexOf("id '") + 4;
    var beforeSecondId = eachLine.IndexOf("id '", beforeFirstId) + 4;
    
    // Now use the extention method to get the two number-strings:
    var firstId = eachLine.GetNumbersFromPos(beforeFirstId);
    var secondId = eachLine.GetNumbersFromPos(beforeSecondId);
    

    This will give you the numbers as strings in firstId and secondId, which you can then store, or parse to int, or whatever you need.

提交回复
热议问题