我有一个巨大的 (~500K) 文本文件,如下所示:
{ // H-20e180a.wav
{-7,5,-4,-1,-9,2,-5,-1,2,-12,12,-33,34,-48,41,-40,16,20,730,4751,3861},
{-7,5,-4,-1,-9,2,-5,-1,2,-12,12,-33,34,-48,41,-40,16,20,}
}
(注意:在实际文件中有一些额外的困惑,每个数组对要长得多~140 elts)。
我希望创建一个 C#/.NET 例程,允许我提取一对数组:
int [] [] elev_neg20__azi_180 = ArraysForLocation( -20, 180 );
我的基本策略是什么?
从我编写 BASIC 代码开始,我会一次读一行,寻找“//H”,然后提取 2 个数字,如果它们匹配,我会处理接下来的两行。但从那以后事情可能已经发生了变化!
我猜想通读整个文件没有捷径...
最佳答案
From my days of coding BASIC, I would read in one line at a time, looking for '// H', then extract the 2 numbers, and if they match I would process the next two lines.
以同样的方式处理它。使用System.IO.StreamReader
你可以重复ReadLine
直到找到所需的部分,阅读接下来的两行数据,然后 Close
.那么String.Split
逗号分隔值和 Convert.ToInt32
.
实际上您可能不会显式调用 Close
。 StreamReader
类实现了 IDisposable
,因此最佳做法是将其包装在 using
语句中(它会自动调用 Dispose
这将关闭流)。
using (var reader = new StreamReader("somefile.txt"))
{
string line = reader.ReadLine();
}
解析包含一行数据的字符串可以像这样完成:
string line = "{-7,5,-4,-1,-9,2,-5,-1,2,-12,12,-33,34,-48,41,-40,16,20,730,4751,3861},";
var regex = new Regex("[{},]");
int[] ints = regex.Replace(line, " ").Trim().
Split(new char[] { ' ' }).Select(int.Parse).ToArray();
从方法返回数组的一个选项是使用 out
值。这样你的正常返回值就可以用来表示成功。像这样的方法签名:
public bool ArraysForLocation(int x, int y, out int[] array1, out int[] array2)
可以这样调用:
int[] a1;
int[] a2;
bool ok = ArraysForLocation(-20, 180, out a1, out a2);
I'm guessing that there is no shortcut to reading through the entire file...
除非您要查找的内容位于尾部,否则您不会阅读整个文件。您正在流式传输 数据,因此一次只读取一行。除非文件内容已排序,以便您可以使用 FileStream.Seek
进行二进制搜索。 ,那么您需要通读文件,直到找到您要查找的数据。
关于c# - 从文本文件中提取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19369144/