Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to parse text file (space delimited numbers)?

Given a data file delimited by 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

Thank you

like image 770
q0987 Avatar asked May 20 '11 00:05

q0987


2 Answers

var fileContent = File.ReadAllText(fileName);
var array = fileContent.Split((string[])null, StringSplitOptions.RemoveEmptyEntries);

if you have numbers only and need a list of int as a result, you can do this:

var numbers = array.Select(arg => int.Parse(arg)).ToList();
like image 92
Alex Aza Avatar answered Sep 21 '22 02:09

Alex Aza


It depends on the kind of array you want. If you want to flatten everything into a single-dimensional array, go with Alex Aza's answer, otherwise, if you want a 2-dimensional array that maps to the lines and elements within the 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();

Be aware that there is no error handling, so if parsing fails, the above code will throw an exception.

like image 34
Quick Joe Smith Avatar answered Sep 24 '22 02:09

Quick Joe Smith