繁体   English   中英

从字符串加载板并存储在二维数组中

[英]Load board from string and store in two dimensional array

我试图将由1和0组成的板存储在二维数组中。 我试图将3组3个值返回到数组中,但是它说csvArray [] []中应该有一个值。

我已经创建了一个1和0的字符串,并将它们拆分为以“ \\ n”分隔的子字符串

    int[][] loadBoardfromString(string Data)
    {
        string csvBoard = "0,1,0\n2,0,1\n0,0,1";
        string[] csvArray = csvBoard.Split('\n');
        return csvArray[][];                        
    }

这是您需要的:

    string csvBoard = "0,1,0\n2,0,1\n0,0,1";
    int[][] csvArray =
        csvBoard
            .Split('\n') // { "0,1,0", "2,0,1", "0,0,1" }
            .Select(x =>
                x
                    .Split(',') // { "X", "Y", "Z" }
                    .Select(y => int.Parse(y)) // { X, Y, Z }
                    .ToArray())
            .ToArray();

我猜这是某种家庭作业,因此我将尝试使用最基本的解决方案,以便老师不知道:)。

        string csvBoard = "0,1,0\n2,0,1\n0,0,1";
        // This splits the csv text into rows and each is a string
        string[] rows = csvBoard.Split('\n');
        // Need to alocate a array of the same size as your csv table 
        int[,] table = new int[3, 3];
        // It will go over each row
        for (int i = 0; i < rows.Length; i++)
        {
            // This will split the row on , and you will get string of columns
            string[] columns = rows[i].Split(',');
            for (int j = 0; j < columns.Length; j++)
            {
                //all is left is to set the value to it's location since the column contains string need to parse the values to integers
                table[i, j] = int.Parse(columns[j]);
            }
        }

        // For jagged array and some linq
        var tableJagged = csvBoard.Split('\n')
                                  .Select(row => row.Split(',')
                                                 .Select(column => int.Parse(column))
                                                 .ToArray())
                                   .ToArray();

这是我关于如何改善此问题的建议,以便您学习概念。 提出一种更适用的方法,无论大小如何,该方法都可以溢出任何随机的csv,并返回二维数组而不是锯齿状数组。 当有人没有在您的方法中放入有效的csv文本作为参数时,也要尝试处理这种情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM