c#读文件,求解答
C#读文本文件(.txt)中float类型数据,文件中部分内容如下:
-9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 46.421867 47.154938 47.737938 48.243614 48.729698 49.124817 49.475563 49.799686 49.953014 49.991188 49.897472 49.726665 49.477692 49.169579 48.855618 48.492619 48.079506 47.699543 47.325279 46.858459 46.426254 45.998207 45.522137 45.100704 44.722805 44.363735 44.064838 43.801971 43.663723 43.603817 43.680141 43.873699 44.142914 44.608578 45.113960 45.691082 46.366165 47.047710 47.753540 48.733620 49.620865 50.537239 51.493824 52.326302 53.000473 53.627644 54.088291 54.426739 54.665546 54.803265 54.811871 54.709373 54.532959 54.322399 54.010723 53.678448 53.310925 52.880295 52.346054
我想把读出来的数据保存在float[]数组中,求帮忙,感激不尽……
------解决方案--------------------一次性读取所有数据作为一个字符串,然后通过空格进行Split操作,然后转型放到float数组中
string s = "-9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.000000 -9999.0000 ...";
float[] f = new float[s.Split(' ').Length];
for(int i = 0;i < s.Split(' ').Length;i++)
{
f[i] = float.Parse(s.Split(' ')[i].ToString());
}
------解决方案--------------------C# code
string s = File.ReadAllText(@"c:\test.txt"));
string[] values = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
float[] rs = new float[values.Length];
for (int i = 0; i < rs.Length; i++)
rs[i] = float.Parse(values[i]);
------解决方案--------------------
第一行最后多了个)