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

前端 未结 3 2185
北恋
北恋 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:22

    A very basic solution is read the lines, split them and find valid integers:

    List test = new List();
    List error = new List();
    
    using (var reader = new StreamReader(@"D:\Temp\AccessEmail.txt")){
         string line;
         while ((line = reader.ReadLine()) != null){   
            //split the line
            string[] parts = line.Split(new[]{"Error"}, StringSplitOptions.None);
    
            //get valid integers
            test.Add(GetInt(parts[0].Split(' ', '\'')));
            error.Add(GetInt(parts[1].Split(' ', '\'')));
         }
    }
    
    //print the number of elements in the lists
    Console.WriteLine(test.Count); 
    Console.WriteLine(error.Count);
    

    int GetInt(string[] a){
        int i = 0;
    
        foreach (string s in a)
           int.TryParse(s, out i);
    
        return i;
    }
    

提交回复
热议问题