如何从字符串输入中提取数组?

时间:2017-11-16 07:18:28

标签: java

输入采用这种格式......

String input = "3 12#45#33 94#54#23 98#59#27";

要在此数组中提取...

int[][] array = new int[3][3];

1 个答案:

答案 0 :(得分:0)

您可以拆分字符串然后遍历数组。结果是这样的:

String input = "3 12#45#33 94#54#23 98#59#27";
String[] strings = input.split(" ");

int size = Integer.parseInt(strings[0]);
int[][] result = new int[size][size];

for( int i = 0; i < strings.length - 1; i++ ){
    String[] strings2 = strings[i + 1].split("#");
    for( int j = 0; j < strings2.length; j++ ){
        result[i][j] = Integer.parseInt(strings2[j]); // add the parsed int to result
    }
}