前言:处理输入问题,看似简单,实则有些细节需要注意。原因是,笔试以及面试撕代码时碰到下面的场景,一时之间不知道怎么处理。
输入字符串实例: [[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])); } } }总结: 见到字符串替换,切割就行了。使用正则表达容易出错。