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

我正在尝试将由 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[][];                        

    }


浮云间
浏览 71回答 2
2回答

心有法竹

这是您需要的:    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();

人到中年有点甜

我猜这是某种家庭作业,所以我会尝试使用最基本的解决方案,这样老师就不知道了:)。&nbsp; &nbsp; &nbsp; &nbsp; string csvBoard = "0,1,0\n2,0,1\n0,0,1";&nbsp; &nbsp; &nbsp; &nbsp; // This splits the csv text into rows and each is a string&nbsp; &nbsp; &nbsp; &nbsp; string[] rows = csvBoard.Split('\n');&nbsp; &nbsp; &nbsp; &nbsp; // Need to alocate a array of the same size as your csv table&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; int[,] table = new int[3, 3];&nbsp; &nbsp; &nbsp; &nbsp; // It will go over each row&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < rows.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // This will split the row on , and you will get string of columns&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string[] columns = rows[i].Split(',');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j < columns.Length; j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //all is left is to set the value to it's location since the column contains string need to parse the values to integers&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table[i, j] = int.Parse(columns[j]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // For jagged array and some linq&nbsp; &nbsp; &nbsp; &nbsp; var tableJagged = csvBoard.Split('\n')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(row => row.Split(',')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Select(column => int.Parse(column))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.ToArray())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.ToArray();这是我关于如何改进它以便学习这些概念的建议。制作一个更适用的方法,无论大小如何,它都可以溢出任何随机 csv,并返回一个二维数组而不是锯齿状数组。当有人没有将有效的 csv 文本作为参数放入您的方法时,也尝试处理这种情况。
打开App,查看更多内容
随时随地看视频慕课网APP