为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
浮云间 2022-11-22 15:33:19
我正在尝试将由 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[][];                            }
查看完整描述

2 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

这是您需要的:


    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();


查看完整回答
反对 回复 2022-11-22
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

我猜这是某种家庭作业,所以我会尝试使用最基本的解决方案,这样老师就不知道了:)。


        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 文本作为参数放入您的方法时,也尝试处理这种情况。


查看完整回答
反对 回复 2022-11-22
  • 2 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信