【问题标题】:How do I create an array of each line in a text file? [closed]如何在文本文件中创建每一行的数组? [关闭]
【发布时间】:2016-02-02 21:14:33
【问题描述】:

我是 C# 新手! 每当我想在其他程序中解析来自 .txt 文件的信息时,我都会创建一个循环来读取整个文件并将每一行保存为以该文件命名的数组。我不知道如何在 C# 中做到这一点并寻求帮助,这是我的流程示例:

//This is not a programming language, just my thought process on how it works;

loop
{
    ReadFile "File1.txt", Line i, save as vTempLine
    if (vTempLine != null)
    {
        vCount = i
        vFile1Array[i] = vTempLine
    }
    else
    {
        vCountLoop1 = vCount
        vTempLine = ""
        vCount = ""
        Break
    }
}

我来自AutoHotkey,这是一个小例子。基本上:

  1. 循环重复直到中断

  2. 第一个命令一次读取一行.txt 文件,告诉读取行i,这是当前循环的行。将此行保存为变量字符串vTempLine

  3. 检查以确保行存在,然后将当前行数保存为vCount,将当前行保存为vFile1Array,其中当前数组计数等于循环。这样,每个数组编号都等于它所形成的行(跳过起始数组变量 0)。

  4. 如果读取的文件中的行不存在,则假定文件结束并将临时变量保存到长期变量中,然后关闭这些临时变量并中断循环。

  5. 最终结果会有两个变量,一个名为vCountLoop1,它包含文件中的行数。

  6. 第二个变量是一个数组,每个数组变量存储为文本文件中的一行(跳过数组0的存储)。

【问题讨论】:

  • 谷歌StreamReaderList<string>List.AddList.ToArray()
  • 你应该解释发生了什么问题;你只是在说你现在想要做什么。
  • var myArray = File.ReadAllLines("File1.txt")See here
  • @Benjamin W. - 没有任何问题,我刚接触 C# 并试图掌握如何从文本文件中保存数组。
  • 只是说这个问题目前还不是很清楚:你说“我该怎么做X?”,然后你发布代码并描述代码的作用。还是代码应该做的?

标签: c# arrays loops variables readfile


【解决方案1】:

这段代码不是很好,但你在考虑这样的事情吗?

string vTempLine;    // Not needed to be declared outside the loop
int i = 0;
int vCountLoop1 = 0; // Not needed: Might be the same as i
Dictionary<int, string> vFile1Array = new Dictionary<int, string>(); // Or use a List<string>

using (StreamReader sr = new StreamReader("File1.txt")) 
{
    while (sr.Peek() >= 0) 
    {
        // if statement is not needed here
        i++;
        vTempLine = sr.ReadLine();
        vCountLoop1 = i;
        vFile1Array[i] = vTempLine; 
    }
}

【讨论】:

  • 当你说“不需要在循环外声明”时,如果只在循环内声明变量,会在循环结束时从内存中删除吗?
  • 我认为 cmets 中建议的 File.ReadAllLines("File1.txt") 是一个更好的解决方案。如果您要自己执行此操作,我会使用 List&lt;string&gt; 并在需要时将其转换为数组 (.ToArray()),而不是字典。
  • @EricJ。这仅适用于 1 行代码吗?
  • 是的。 string[] vFile1Array = File.ReadAllLines("File1.txt");
  • @EricJ。好的谢谢。你知道我怎么能回忆起保存在数组中的变量数量吗?因为我还需要获取文件中的行数
猜你喜欢
  • 1970-01-01
  • 2020-05-11
  • 2020-07-02
  • 2017-02-16
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多