刷题中二维数组字符串输入处理问题

前言:处理输入问题,看似简单,实则有些细节需要注意。原因是,笔试以及面试撕代码时碰到下面的场景,一时之间不知道怎么处理。

刷题中处理输入问题

输入字符串实例:
[[1,2,3],[2,3,4],[4,5,6]]
[[1, 2]]
[[]]

下面测试的输出情况:按一维数组打印
[1, 2, 3]
[2, 3, 4]
[4, 5, 6]

[1, 2]

[0]

注意:
两个二维数组之间分隔],[中间还有空格的情况

public class Main {
    public static void main(String[] args) {

        String input1 = "[[1,2,3],[2,3,4],[4,5,6]]";
        String input2 = "[[1, 2]]";
        String input3 = "[[]]";
        int[][] handle = handle(input1);
        print(handle);
        System.out.println();
        handle = handle(input2);
        print(handle);
        System.out.println();
        handle = handle(input3);
        print(handle);
        System.out.println();

    }
    public static int[][] handle(String input){
        // 首先去掉前后的两重中括号, 将],[替换为]#[再利用空格分隔
        // 特别注意:这里有两个一维数组之间的分隔到底是],[ 还是], [ 后面有个空格,需要视情况而定。元素前后有空格无需考虑
        String[] replace = input.substring(1, input.length()-1).replace("],[", "]#[").split("#");
        int rows = replace.length;
        int cols = replace[0].split(",").length; //
/*      for(String sub :replace)
            System.out.println(sub);
        System.out.println("rows: "+rows + " cols: " + cols);*/

        int[][] array = new int[rows][cols]; // 返回数组
        loop:
        for (int i = 0; i < rows; i++) {
            String[] tmp = replace[i].substring(1, replace[i].length()-1).split(","); // 去掉前后中括号,再以,分割
            for (int j = 0; j < cols; j++) {
                if(tmp[j].length() == 0) {
                    break loop; // 若数组元素为空则说明异常。若是正常输入,这里无需考虑判断跳出
                }
                array[i][j] = Integer.parseInt(tmp[j].trim()); // trim目的是去掉前后空格,例如 1, 2
            }
        }
        return array;
    }

    public static void print(int[][] array){
        int rows = array.length;
        int cols = array[0].length;
        for (int i = 0; i < rows; i++) {
            System.out.println(Arrays.toString(array[i]));
        }
    }
}

总结:
见到字符串替换,切割就行了。使用正则表达容易出错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值