java 将字符串转换为二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29546564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:28:47  来源:igfitidea点击:

Convert String into a two dimensional array

javastringmultidimensional-arrayconverter

提问by Phoenix

I try to convert this string

我尝试转换这个字符串

s=[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]
into a two dimensional array like this
{4, 2, 2, 4},
{3, 4, 5, 6},
{6, 7, 8,9},
{3, 2, 1, 4}

s=[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]
变成这样的二维数组
{4, 2, 2, 4},
{3, 4, 5, 6},
{6, 7, 8,9},
{3, 2, 1, 4}

by use this code

通过使用此代码

 int e=s.replaceAll("\[", "").replaceAll(" ","").replaceAll("],","]").length();
        String[] rows1 = s.replaceAll("\[", "").replaceAll(" ","").replaceAll("],","]").substring(0, e-2).split("]");

        String[][] matrix1 = new String[4][4]; 
        int r1 = 0;
        for (String row1 : rows1) {
            matrix[r1++] = row1.split(",");
        }

        System.out.println(Arrays.deepToString(matrix1));

But is have problem like this

但是有这样的问题

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at test.main(test.java:94)

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 at test.main(test.java:94)

Can you help me find a solution?

你能帮我找到解决办法吗?

回答by Md. Nasir Uddin Bhuiyan

I think this code will help you. Read the all comments carefully.

我认为这段代码会对你有所帮助。仔细阅读所有评论。

     String s="[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";
     s=s.replace("[","");//replacing all [ to ""
     s=s.substring(0,s.length()-2);//ignoring last two ]]
     String s1[]=s.split("],");//separating all by "],"

     String my_matrics[][] = new String[s1.length][s1.length];//declaring two dimensional matrix for input

     for(int i=0;i<s1.length;i++){
         s1[i]=s1[i].trim();//ignoring all extra space if the string s1[i] has
         String single_int[]=s1[i].split(", ");//separating integers by ", "

         for(int j=0;j<single_int.length;j++){
             my_matrics[i][j]=single_int[j];//adding single values
         }
     }

     //printing result
     for(int i=0;i<4;i++){
         for(int j=0;j<4;j++){
             System.out.print(my_matrics[i][j]+" ");
         }
         System.out.println("");
     }

[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]

[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]

Logic: 1) replacing all [ to "" now I have-> 4, 2, 2, 4], 3, 4, 5, 6], 6, 7, 8, 9], 3, 2, 1, 4]]

逻辑:1) 将所有 [ 替换为 "" 现在我有-> 4, 2, 2, 4], 3, 4, 5, 6], 6, 7, 8, 9], 3, 2, 1, 4] ]

2) Separating all by "]," now I have->

2)用“]”分隔,现在我有->

A) 4, 2, 2, 4

A) 4, 2, 2, 4

B) 3, 4, 5, 6

B) 3、4、5、6

c) 6, 7, 8, 9

c) 6, 7, 8, 9

d) 3, 2, 1, 4

d) 3, 2, 1, 4

3) Separating A B C D by ", " now I have->

3) 用 ", " 分隔 ABCD 现在我有 ->

A) a) 4 b) 2 c) 2 d) 4

A) a) 4 b) 2 c) 2 d) 4

B) a) 3 b) 4 c) 5 d) 6

B) a) 3 b) 4 c) 5 d) 6

c) a) 6 b) 7 c) 8 d) 9

c) a) 6 b) 7 c) 8 d) 9

d) a) 3 b) 2 c) 1 d) 4

d) a) 3 b) 2 c) 1 d) 4

回答by Michael Dz

Solution using Java streams:

使用 Java 流的解决方案:

String[][] arr = Arrays.stream(str.substring(2, str.length() - 2).split("\],\["))
.map(e -> Arrays.stream(e.split("\s*,\s*"))
.toArray(String[]::new)).toArray(String[][]::new);

回答by Bram

This just doesn't add the comma's at the end of the line:

这只是不会在行尾添加逗号:

    String s = "[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";
    for (String l: s.split("\]\s*,\s*\[")) {
        l = l.replaceAll("\[", "").replaceAll("\]", "");
        System.out.println("{" + l + "}");
    }

回答by kyle

Assuming that the input string will always be in that format, with 4 integers between each bracket, I think the best way to do it would simply be to use a Scannerobject and it's nextInt() method which will ignore the brackets and comma's and just find the numbers. Then put them into a 2d array like how you would with a loop.

假设输入字符串总是采用那种格式,每个括号之间有 4 个整数,我认为最好的方法就是使用Scanner对象,它的 nextInt() 方法将忽略括号和逗号,只是找到数字。然后将它们放入一个二维数组中,就像使用循环一样。

It kinda gets rid of all the fun you were having with removing the brackets though, so it's not really better in terms of making an exercise out of this.

不过,它有点摆脱了删除括号时的所有乐趣,因此在进行练习方面并不是更好。

回答by Shar1er80

Try this...

试试这个...

String s="[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";

// Split on this delimiter
String[] rows = s.split("], \[");
for (int i = 0; i < rows.length; i++) {
    // Remove any beginning and ending braces and any white spaces
    rows[i] = rows[i].replace("[[", "").replace("]]", "").replaceAll(" ", "");
}

// Get the number of columns in a row
int numberOfColumns = rows[0].split(",").length;

// Setup your matrix
String[][] matrix = new String[rows.length][numberOfColumns];

// Populate your matrix
for (int i = 0; i < rows.length; i++) {
    matrix[i] = rows[i].split(",");
}
// Display your matrix
System.out.println(Arrays.deepToString(matrix));

Results:

结果:

enter image description here

在此处输入图片说明