这是我想分割成二维数组的文本文件
"YHOO",36.86,21,13873900,37.00
"GOOG",684.11,1114,1821650,686.72
"MSFT",50.54,3993,31910300,50.65
"AAPL",94.40,28201,39817000,94.26
这是我实现的代码但是它不起作用
String input = File.ReadAllText(@"....DatastockInfo.txt");
int i = 0, j = 0;
string[,] result = new string[3, 5];
foreach (var row in input.Split('n'))
{
j = 0;
foreach (var col in row.Trim().Split(','))
{
result[i, j] = string.Parse(col.Trim());
j++;
}
i++;
}
锯齿形数组String[][]
(数组的数组)通常比二维数组String[,]
:
string[][] result = File
.ReadLines(@"....DatastockInfo.txt")
.Select(line => line.Split(','))
.ToArray();
如果你坚持使用2D数组你就必须使用效率较低的代码
string[] lines = File.ReadAllLines(@"....DatastockInfo.txt");
string[,] result = null;
for (int i = 0; i < lines.Count; ++i) {
string[] items = lines.Split(',');
if (null == result)
result = new string[lines.Count, items.Length];
for (int j = 0; j < items.Length; ++j)
result[i, j] = items[j];
}
数组大小错误。此外,你不需要串。解析,因为Split的输出是IEnumerable of strings
int i = 0, j = 0;
string[,] result = new string[4, 5];
foreach (var row in input.Split('n'))
{
j = 0;
foreach (var col in row.Trim().Split(','))
{
result[i, j] = col.Trim();
j++;
}
i++;
}