将文件读取到数组
本文关键字:数组 读取 文件 | 更新日期: 2023-09-27 18:02:08
我正在读取并计算文件中的行数,然后初始化一个具有与行数相同的空格数的数组。然后再次读取文件,并将每行赋值给数组的该位置。例如,第一行将存储在索引位置0中。我有以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace testProg
{
class program
{
static void main(){
Console.WriteLine("enter your filename for reading!");
fileName = Console.ReadLine();
using (StreamReader rs = new StreamReader(fileName))
{
string line2;
while ((line2 = rs.ReadLine()) != null)
{
arraysize = arraysize+1;//this goes through and gets the number of lines
}
}
Console.WriteLine(arraysize);
string[] unenc = new string[arraysize]; //this creates the array dynamically
int i = -1;//starts at position -1 then +1 so starts at 0
using (StreamReader fr = new StreamReader(fileName))
{
string linefinal;
while ((linefinal = fr.ReadLine()) != null)
{
Console.WriteLine(linefinal);//this will write the current line
unenc[i + 1] = linefinal;// this should store the string above in the current position
Console.WriteLine(unenc[i]);//this should output the same line it does not the index is just empty ? but it should be stored yet it is not
}
}
}
}
}
问题是您没有将i
的增量值保存在任何地方。
你可以这样修改代码:
while ((linefinal = fr.ReadLine()) != null)
{
Console.WriteLine(linefinal);
unenc[i + 1] = linefinal;
Console.WriteLine(unenc[i]);
i++;
}
所以你在注释中的查询是
数组不会更新
unenc[i+1]
所在的section中i的值吗?
i + 1
的作用是返回"i
+ 1
".
如果你想增加这个值,你有两个选择:
返回值后的增量:
var oldValue = i++;
var newValue = i;
返回值前的增量:
var oldValue = i;
var newValue = ++i;
代码优化
你必须读取你的文件两次,以获得行数,这样你就可以发现你的数组有多大。net提供了一个可爱的类,它将在这种情况下帮助你:List<>
.
List<int>
是int[]
的包装器,它动态地管理其内部数组的长度,这意味着当使用数组时,您必须这样做:
var array = int[3];
array[0] = 1;
array[1] = 2;
array[3] = 3:
对于List<int>
,您可以简单地执行以下操作
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
对于数组,如果你想添加另一个元素,你必须将其复制到一个更大的数组中,而对于list,这一切都是在内部完成的。
当然你仍然可以通过var item = list[3];
访问列表。
因此,利用这个,你可以不需要文件的第一次读取,只是不断地添加到一个列表。
考虑使用List对象代替数组。您可以使用Add()方法在读取项时不断添加项。完成后,只需调用List对象上的ToArray()方法即可获得所需的数组。您将拥有匹配每行的所有索引值。
unenc[i + 1] = linefinal;
不太对。我相信你的意思是
unenc[i++] = linefinal;
您的行在执行循环时不会改变i
的值。
简单的方法是使用ArrayList
。请参阅下面的代码片段
ArrayList lines = new ArrayList();
using (StreamReader rs = new StreamReader(@"C:'Users'vimal'Desktop'test.txt"))
{
string line = null;
while ((line = rs.ReadLine()) != null)
{
lines.Add(line);
}
}