Java中String二维数组转换char二维数组

一、场景:

写leetcode37.解数独算法的时候想用测试用例,结果发现测试用例都是字符串如图

输入:board = [["5","3",".",".","7",".",".",".","."],
			   ["6",".",".","1","9","5",".",".","."],
			   [".","9","8",".",".",".",".","6","."],
			   ["8",".",".",".","6",".",".",".","3"],
			   ["4",".",".","8",".","3",".",".","1"],
			   ["7",".",".",".","2",".",".",".","6"],
			   [".","6",".",".",".",".","2","8","."],
			   [".",".",".","4","1","9",".",".","5"],
			   [".",".",".",".","8",".",".","7","9"]]

然后题目开始又是传入char[][]类型的(也可以把参数变成String[][],就不)

class Solution {
    public void solveSudoku(char[][] board) {

    }
}

然后搜了一下网上也没有,于是乎就想弄一个偷懒下次使用也方便的方发
在这里插入图片描述

二、方法

public static char[][] string2ToChar2(String[][] board) {
    char[][] chars = new char[board.length][board.length];
    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board.length; j++) {
            chars[i][j] = board[i][j].charAt(0);
        }
    }
    return chars;
}

三、测试

public static void main(String[] args) {
    String[][] board = {{"5","3",".",".","7",".",".",".","."},
                        {"6",".",".","1","9","5",".",".","."},
                        {".","9","8",".",".",".",".","6","."},
                        {"8",".",".",".","6",".",".",".","3"},
                        {"4",".",".","8",".","3",".",".","1"},
                        {"7",".",".",".","2",".",".",".","6"},
                        {".","6",".",".",".",".","2","8","."},
                        {".",".",".","4","1","9",".",".","5"},
                        {".",".",".",".","8",".",".","7","9"}};
    char[][] chars = string2ToChar2(board);
    System.out.println("=========验证==========");
    for (int i = 0; i < chars.length; i++) {
        for (int j = 0; j < chars.length; j++) {
            System.out.print(chars[i][j]);
        }
        System.out.println();
    }

}

测试结果

image-20220426144029220

  • 3
    点赞
  • 5
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:1024 设计师:我叫白小胖 返回首页
评论

打赏作者

黄铜小马

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值