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

℡╲_俬逩灬. 提交于 2019-12-10 14:13:28

问题


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


回答1:


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();



回答2:


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.




回答3:


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




回答4:


I couldn't get Quick Joe Smith's answer to work, so I modified it. I put the modified code into a static method within a "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 was parsing for double as opposed to 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);


来源:https://stackoverflow.com/questions/6066154/c-sharp-how-to-parse-text-file-space-delimited-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!