文本文件读入数组 [英] Text file read into arrays

查看:83
本文介绍了文本文件读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#初学者在这里请耐心等待。

我有一系列包含数字值的.txt文件,我想从命令行指定它们然后放置内容将每个.txt文件放入一个单独的数组中,以便我的程序稍后进行排序。

(.txt文件包含必须从最低到最高排序的数字,反之亦然)

我该怎么做?

我有尝试谷歌搜索答案,但没有找到解决方案。

任何帮助表示感谢。



我尝试过:



我还没有尝试任何事情,因为我不确定如何开始。

C# Beginner here so please bear with me.
I have a series of .txt files that contain number values, and I would like to designate them from the command line and then place the contents of each .txt file into an individual array for my program to sort later.
(the .txt files contain numbers that must be sorted lowest to highest and vice versa)
How can I do this?
I have tried googling the answer but have not found a solution.
Any help appreciated.

What I have tried:

I have yet to try anything as I am unsure how to start.

推荐答案

Hi


欢迎使用C#!



StreamReader类可用于将数据读入应用程序



Hi
Welcome to C#!

The StreamReader class is one that you can use to read data into your application

using(var reader = new StreamReader("C:\\PathOfFile.txt"))
{

}





您可以在循环中使用 ReadLine()方法将行读入集合或 ReadToEnd()读取整个内容并在之后拆分行。



You can use the method ReadLine() in a loop to read the lines into a collection or ReadToEnd() to read the whole thing and split the lines up afterwards.


另一个选项是使用 File.ReadLines 方法(参见文件.ReadLines方法(System.IO)| Microsoft Docs [ ^ ])。



然后你可以使用 foreach 循环遍历这些行,像这样:

Another option is to use the File.ReadLines method (see File.ReadLines Method (System.IO) | Microsoft Docs[^]).

You can then either use a foreach loop to iterate through the lines, like so:
foreach(string line in File.ReadLines("myFile.txt"))
{
  // Do something with line
}



或者您可以使用LINQ直接填充数组(确保包含一个用于System.Linq的)。例如,要从每行包含单个整数的文件中创建数组,您可以执行以下操作:


Or you can use LINQ to populate an array directly (make sure to include a using for System.Linq). For example, to make an array from a file where each line contains a single integral number, you could do the following:

int[] myNumbers = File.ReadLines("myFile.txt")
  .Select(line => int.Parse(line))
  .ToArray();


这篇关于文本文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆