我想从一个未知行数/列数的CSV文件中生成一个2D数组。列计数是基于标题数据固定的。我需要能够将其处理为跨行和跨列的网格,因此需要数组。
目前,我可以将数据拆分成行,然后将每行拆分成组件。然后我将每一行添加到一个列表中。这一切似乎都运行得很好。
我不能做的是将一个字符串数组列表转换成一个二维数组。
它当前在字符串newCSV =csvFile.ToArray()上失败;with error不能隐式地将类型' string‘转换为'string *,*’,所以我显然没有正确地声明一些东西-我就是不知道是什么!
List<string[]> csvFile = new List<string[]>();
void Start()
{
// TODO: file picker
TextAsset sourceData = Resources.Load<TextAsset>("CSVData");
if (sourceData != null)
{
// Each piece of data in a CSV has a newline at the end
// Split the base data into an array each time the newline char is found
string[] data = sourceData.text.Split(new char[] {'\n'} );
for (int i = 0; i < data.Length; i ++)
{
string[] row = data[i].Split(new char[] {','} );
Debug.Log(row[0] + " " + row[1]);
csvFile.Add(row);
}
string[,] newCSV = csvFile.ToArray();
} else {
Debug.Log("Can't open source file");
}
发布于 2019-09-18 20:24:00
您可以使用此函数来获取2d数组。
static public string[,] SplitCsvGrid(string csvText)
{
string[] lines = csvText.Split("\n"[0]);
// finds the max width of row
int width = 0;
for (int i = 0; i < lines.Length; i++)
{
string[] row = SplitCsvLine(lines[i]);
width = Mathf.Max(width, row.Length);
}
// creates new 2D string grid to output to
string[,] outputGrid = new string[width + 1, lines.Length + 1];
for (int y = 0; y < lines.Length; y++)
{
string[] row = SplitCsvLine(lines[y]);
for (int x = 0; x < row.Length; x++)
{
outputGrid[x, y] = row[x];
// This line was to replace "" with " in my output.
// Include or edit it as you wish.
outputGrid[x, y] = outputGrid[x, y].Replace("\"\"", "\"");
}
}
return outputGrid;
}
发布于 2019-09-18 18:07:02
https://stackoverflow.com/questions/57997405
复制相似问题