C # - how to parse a text file (delimited numbers)?

Given a data file limited to a space,

10 10 10 10 222 331 2 3 3 4 45 4 2 2 4 

How to read this file and load into an array

thanks

+6
source share
4 answers
 var fileContent = File.ReadAllText(fileName); var array = fileContent.Split((string[])null, StringSplitOptions.RemoveEmptyEntries); 

If you only have numbers and you need an int list, you can do this:

 var numbers = array.Select(arg => int.Parse(arg)).ToList(); 
+13
source

It depends on the type of array you want. If you want to smooth everything into a one-dimensional array, go with Alex Aza's answer, otherwise, if you want a 2-dimensional array to map to strings and elements in a text file:

 var array = File.ReadAllLines(filename) .Select(line => line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) .Where(line => !string.IsNullOrWhiteSpace(line)) // Use this to filter blank lines. .Select(int.Parse) // Assuming you want an int array. .ToArray(); 

Keep in mind that there is no error handling, so if parsing is not performed, the above code throws an exception.

+6
source

You will be interested in StreamReader.ReadLine() and String.Split()

+1
source

I could not get the Quick Joe Smith response to work, so I modified it. I put the modified code in a static method in the "FileReader" class:

 public static double[][] readWhitespaceDelimitedDoubles(string[] input) { double[][] array = input.Where(line => !String.IsNullOrWhiteSpace(line)) // Use this to filter blank lines. .Select(line => line.Split((string[])null, StringSplitOptions.RemoveEmptyEntries)) .Select(line => line.Select(element => double.Parse(element))) .Select(line => line.ToArray()) .ToArray(); return array; } 

For my application, I understood double, not int. To call the code, try using something like this:

 string[] fileContents = System.IO.File.ReadAllLines(openFileDialog1.FileName); double[][] fileContentsArray = FileReader.readWhitespaceDelimitedDoubles(fileContents); Console.WriteLine("Number of Rows: {0,3}", fileContentsArray.Length); Console.WriteLine("Number of Cols: {0,3}", fileContentsArray[0].Length); 
0
source

Source: https://habr.com/ru/post/888603/


All Articles