首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将行数/列数未知的CSV读入Unity数组

将行数/列数未知的CSV读入Unity数组
EN

Stack Overflow用户
提问于 2019-09-19 00:45:10
回答 2查看 895关注 0票数 1

我想从一个未知行数/列数的CSV文件中生成一个2D数组。列计数是基于标题数据固定的。我需要能够将其处理为跨行和跨列的网格,因此需要数组。

目前,我可以将数据拆分成行,然后将每行拆分成组件。然后我将每一行添加到一个列表中。这一切似乎都运行得很好。

我不能做的是将一个字符串数组列表转换成一个二维数组。

它当前在字符串newCSV =csvFile.ToArray()上失败;with error不能隐式地将类型' string‘转换为'string *,*’,所以我显然没有正确地声明一些东西-我就是不知道是什么!

代码语言:javascript
运行
复制
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");
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-19 04:24:00

您可以使用此函数来获取2d数组。

代码语言:javascript
运行
复制
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;
}
票数 2
EN

Stack Overflow用户

发布于 2019-09-19 02:07:02

由于您的数据是以表的形式存在的,所以我强烈建议您使用DataTable,而不是像您目前用来建模/保存csv中的数据那样的2d数组。

这种数据结构提供了大量的预烘焙功能,这些功能将使处理数据变得更加容易。

如果采用此方法,则还可以使用this,它将使用CSV数据的结构将CSV数据复制到DataTable中,以创建DataTable。

它非常容易配置和使用。

只有一个小技巧,只要有可能,你应该总是尝试使用最适合你的任务的数据结构。想想你用来建造房子的数据结构和算法,虽然你当然可以使用螺丝刀敲钉子,但使用锤子要容易得多,效率也更高。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57997405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档