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]]

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

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

A) 4, 2, 2, 4

B) 3, 4, 5, 6

c) 6, 7, 8, 9

d) 3, 2, 1, 4

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

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

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

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

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

Answer from Md. Nasir Uddin Bhuiyan on Stack Overflow
🌐
Reddit
reddit.com β€Ί r/javahelp β€Ί how to turn a string of a 2d array into a 2d array?
r/javahelp on Reddit: How to turn a string of a 2D array into a 2D array?
February 25, 2024 -

Hello

I have an input of a 2D array in the form of a string. And I want to turn it into a 2D array and store it.

I have tried using .replace() but it’s not working as I expected.

An example of an input is

String x = β€œ{ {F, 40 , 40 , 2000},{L, 60 , 60 , 1000},{F, 40 , 40 , 2000}}”

And I want to turn it into an array like

String [][] y = { {β€œF” , β€œ40” , β€œ40” , β€œ2000”}, {β€œB” ,β€œ60” , β€œ60” , β€œ1000”}, {β€œF” , β€œ40” , β€œ40” , β€œ2000”}}

I saw some tips on using replace() and split() but I am unsure how to use them to achieve what I want or if I need another function to solve this.

Any tips to help solve this would be appreciated.

Top answer
1 of 5
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 5
1
This is not gonna help you if you are doing a homework. But for real-world usage, here's how such parsing can be done with Google Mug ( example code . recommended internally at Google too): String x = "{ {F, 40 , 40 , 2000},{L, 60 , 60 , 1000},{F, 40 , 40 , 2000}}"; String nested = Substring.between(first('{'), last('}')).from(x).get(); System.out.println( Substring.between('{', '}') .repeatedly() .from(nested) // => [{F, ...}, {L, ...}, {F, ...}] .map(Substring.first(',').repeatedly()::splitThenTrim) .map(items -> items.map(Object::toString).toList()) .toList()); I used toList() to get toString(). But you can change the first toList() to .toArray(String[]::new) and the second to .toArray(String[][]::new). That'll get you the 2D array. Using List is usually preferred over arrays though.
Discussions

java - convert a String array to a 2d array - Stack Overflow
I have a String array like this 3 1 5 5 2 -2 -3 15 -100 20 how can i convert this to a 2d array 1 5 5 2 -2 -3 15 -100 20 3 is the size of 2d public static class convert(String[] lines){ int ... More on stackoverflow.com
🌐 stackoverflow.com
October 27, 2014
java - Create a two dimensional string array anArray[2][2] - Stack Overflow
I'm currently on a self learning Java course and am completely stumped at one of my assignments, can anyone give me some pointers please? Bear in mind that I am completely new to Java so I need it ... More on stackoverflow.com
🌐 stackoverflow.com
Take a String and turn it into a 2d array Java - Stack Overflow
Ok, I was thinking about what to ... done in Java @DanAndrews ... convert in to double , and then use divide and reminder using modulus,so that you can get each integer separately and put it into and 2darray ... You can also iterate through the string and build the 2d array: ... More on stackoverflow.com
🌐 stackoverflow.com
java - String Array to 2D String array - Stack Overflow
I have a String Array, map[] which looks like... ... Thanks a lot. ... Definetely needs to be a 2D array unfortunatly. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Coderanch
coderanch.com β€Ί t β€Ί 754467 β€Ί java β€Ί array-list-strings-array-strings
From array list of strings to a 2d array of strings (Beginning Java forum at Coderanch)
September 20, 2022 - "Today it is Thursday.After 132 days,it will be" ??? wed / sun / mon / thurs --> incomplete javacode ... Assign a value to a numeric variable, then manipulate it, and return a new string. Read tab separated file and store on two dimensional arraylist
Find elsewhere
🌐
Grails
grails.asia β€Ί two-dimensional-string-array-in-java
Two Dimensional String Array in Java - Grails Cookbook
June 29, 2017 - Here is an example code to illustrate: String myTwoDimensionalStringArray[][] = new String[4][]; myTwoDimensionalStringArray[0] = new String[2]; myTwoDimensionalStringArray[1] = new String[4]; myTwoDimensionalStringArray[2] = new String[5]; myTwoDimensionalStringArray[3] = new String[3]; For the code sample above, we are declaring an array of String array.
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 55843322 β€Ί string-to-2d-array
String to 2d Array - Stack Overflow
Check Out: https://www.baeldung.com/java-jagged-arrays ... static char[][][] convert(String text) { String[] strSplit = text.split(" "); char[][][] out = new char[strSplit.length][][]; for (int i = 0; i < strSplit.length; i++) { char[] word = strSplit[i].toCharArray(); char[][] inner = new char[word.length][]; for (int j = 0; j < word.length; j++) { inner[j] = new char[] { word[j] }; } out[i] = inner; } return out; }
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 58053930 β€Ί input-string-into-two-dimensional-array-in-java
Input string into two dimensional array in java - Stack Overflow
And I want to use 2D array to do so, how should I do it? here is my code Β· Scanner str = new Scanner(System.in); int num = str.nextInt(); String dice[][] = new String[5][num]; for (int i = 0; i < 5; i++) { for (int j = 0; j < num; j++) { dice[i][j] = str.nextLine(); } } Where am I doing wrong? java Β·
Top answer
1 of 1
1

Consider using an ArrayList:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Incident {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<String[]> incidentsList = new ArrayList<>();
        int i = 0;
        while (true) {
            System.out.printf("Enter incident %d details:%n", ++i);
            System.out.print("Enter value: ");
            String value = scanner.nextLine();
            System.out.print("Enter postcode: ");
            String postcode = scanner.nextLine();
            System.out.print("Enter month: ");
            String month = scanner.nextLine();
            System.out.print("Enter year: ");
            String year = scanner.nextLine();
            String[] incident = new String[]{value, postcode, month, year};
            incidentsList.add(incident);
            System.out.println("Enter 0 if you would like to exit entering incidents. " +
                    "Any other key if not.");
            String choice = scanner.nextLine();
            if (choice.equals("0")) {
                break;
            }
        }
        System.out.printf("%nYou entered the following incidents:%n");
        for (String[] incident : incidentsList) {
            System.out.println(Arrays.toString(incident));
        }
        System.out.printf("%nincidentsList.get(0)[3] = %s%n", incidentsList.get(0)[3]);
    }
}

Example Usage:

Enter incident 1 details:
Enter value: 1500
Enter postcode: xxxxx
Enter month: jan
Enter year: 2010
Enter 0 if you would like to exit entering incidents. Any other key if not.

Enter incident 2 details:
Enter value: 2000
Enter postcode: xxxxx
Enter month: feb
Enter year: 2000
Enter 0 if you would like to exit entering incidents. Any other key if not.
a
Enter incident 3 details:
Enter value: 1000
Enter postcode: xxxxx
Enter month: sep
Enter year: 2016
Enter 0 if you would like to exit entering incidents. Any other key if not.
0

You entered the following incidents:
[1500, xxxxx, jan, 2010]
[2000, xxxxx, feb, 2000]
[1000, xxxxx, sep, 2016]

incidentsList.get(0)[3] = jan 
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 42380905 β€Ί how-to-convert-a-string-to-a-2d-char-array-java
How to convert a String to a 2D char array JAVA - Stack Overflow
February 22, 2017 - I am trying to convert a string into a 2D char array. So for example, if the input string is: +dd+babd+b_a+ddc The output should be a 2D char array which looks like the following: +dd+ babd +b...
🌐
Blogger
javarevisited.blogspot.com β€Ί 2016 β€Ί 02 β€Ί 6-example-to-declare-two-dimensional-array-in-java.html
6 ways to declare and initialize a two-dimensional (2D) String and Integer Array in Java - Example Tutorial
June 28, 2025 - We have actually declared int[] only Another thing to remember about this code is that if multiple variables are declared in the same line they would be the type of int[] which is one dimensional, not two dimensional like in the following example prices is a 2D array but abc is just a one-dimensional int array. int[] prices[], abc; Again, this is a tricky array concept in Java and that's why you will often find questions on this topic on various Java certifications.
Top answer
1 of 5
7

I would go step by step resolving this task.

First, I would split the original String by a space, then split the results by comma each and afterwards create an array of double out of those values with Double.parseDouble(String value).

public static void main(String[] args) {
    String stringProfile = "0,4.28 10,4.93 20,3.75";

    // split it once by space
    String[] parts = stringProfile.split(" ");

    // create some result array with the amount of double pairs as its dimension
    double[][] results = new double[parts.length][];

    // iterate over the result of the first splitting
    for (int i = 0; i < parts.length; i++) {
        // split each one again, this time by comma
        String[] values = parts[i].split(",");

        // create two doubles out of the single Strings
        double a = Double.parseDouble(values[0]);
        double b = Double.parseDouble(values[1]);

        // add them to an array
        double[] value = {a, b};

        // add the array to the array of arrays
        results[i] = value;
    }

    // then print the result
    for (double[] pair : results) {
        System.out.println(String.format("%.0f and %.2f", pair[0], pair[1]));
    }
}

Yes, these are a lot of lines of code, but most likely more easily understandable than lambda expressions (which are cooler and more elegant in my opinion).

2 of 5
5

What about something like this:

Arrays.stream("0,4.28 10,4.93 20,3.75".split(" ")) //Stream<String>
     .map(s -> 
           Arrays.stream(s.split(",")) // take an individual string like 0,4.28  
                 .map(Double::parseDouble) // and transform it to a double array
                 .toArray(Double[]::new)
      )
     .toArray(Double[][]::new);

the result is

$8 ==> Double[3][] { 
        Double[2] { 0.0, 4.28 }, 
        Double[2] { 10.0, 4.93 }, 
        Double[2] { 20.0, 3.75 } 
}
🌐
Quora
quora.com β€Ί How-do-I-convert-a-1-dimensional-string-array-into-a-2D-string-array
How to convert a 1 dimensional string array into a 2D string array - Quora
Answer (1 of 3): You can not conevert one dimensional array into two dimenssional but you can change the way of storing data ..in two dimension array each element is at position i,j and in one dimensional each element it at i position where i and j are any interger values greater than 0 ..to do s...
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 73996719 β€Ί java-convert-a-2d-array-of-string-in-a-1d-array-of-char
Java: Convert a 2d Array of String in a 1d Array of char - Stack Overflow
1) Loop through the first dimension of the 2d array; 2) Put at the same index of the second array the result of charAt(0) of the first element of the nth element of the first array.