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 OverflowI 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
Solution using Java streams:
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);
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.
java - convert a String array to a 2d array - Stack Overflow
java - Create a two dimensional string array anArray[2][2] - Stack Overflow
Take a String and turn it into a 2d array Java - Stack Overflow
java - String Array to 2D String array - Stack Overflow
try one line version
Arrays.deepToString(tableBornes);
or multiline version
StringBuilder sb = new StringBuilder();
for(String[] s1 : tableBornes){
sb.append(Arrays.toString(s2)).append('\n');
}
String s = sb.toString();
If you want to create one-line representation of array you can use Arrays.deepToString.
In case you want to create multi-line representation you will probably need to iterate over all rows and append result of Array.toString(array[row]) like
String[][] array = { { "a", "b" }, { "c" } };
String lineSeparator = System.lineSeparator();
StringBuilder sb = new StringBuilder();
for (String[] row : array) {
sb.append(Arrays.toString(row))
.append(lineSeparator);
}
String result = sb.toString();
Since Java 8 you can even use StringJoiner with will automatically add delimiter for you:
StringJoiner sj = new StringJoiner(System.lineSeparator());
for (String[] row : array) {
sj.add(Arrays.toString(row));
}
String result = sj.toString();
or using streams
String result = Arrays
.stream(array)
.map(Arrays::toString)
.collect(Collectors.joining(System.lineSeparator()));
Sin,
You have a couple of Off-by-one errors.
Try this:
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j <= n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j-1][i] = Integer.parseInt(currentLine[i]);
}
}
Please let me know if you have any questions!
Since arrays are 0-indexed in Java, you should change your loop initialization variable j to start at 0.
Change:
for (int j = 1; j < n; j++) {
to
for (int j = 0; j < n; j++) {
Also, it seems you want a method to do the conversion, not a class so you should remove this from your method signature and put void since you aren't returning anything from the method.
Change:
public static class convert(String[] lines)
To:
public static void convert(String[] lines)
Also, you should use a different variable to iterate through the string array to make things more cleaner. Since you are trying to use j, you can do that to. Instead of initializing j to 1, you initialize it to 0 as I've said and use j+1 as the index for accessing the lines array.
Here is how your code could look like:
public static void convert(String[] lines)
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 0, k = 1; j < n; j++) {
String[] currentLine = lines[j + 1].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j][i] = Integer.parseInt(currentLine[i]);
}
}
}
You can get your 2d array with a one liner:
int[][] numbers = Arrays.stream("000011112222333344445555".split("(?<=\\G.{4})")).map(s -> (Arrays.stream(s.split("(?<=\\G.{1})")).mapToInt(Integer::parseInt).toArray())).toArray(int[][]::new);
So its fairly easy thing to do.
lets assume your string is str;
char[] strArr = str.toCharArray();
// numbers is the range like 0 to 5 here.
// repeatCount is how many times its repeating like 4 here.
int arr[][] = new int[numbers][repeatCount];
for(int i = 0; i < numbers; i++){
for(int j = 0; j < repeatCount; j++){
arr[i][j] = strArr[i*repeatCount + j]-'0';
}
}
Lastly a precaution, this function will work only if your numbers are single digit, as only one char is being picked.
If you really need it, you can use String.toCharArray on each element array to convert them into an array.
String[] origArr = new String[10];
char[][] charArr = new char[10][];
for(int i = 0; i< origArr.length;i++)
charArr[i] = origArr[i].toCharArray();
If you want to break it up into String[] instead, you could use (thanks Pshemo)
String[] abc = "abc".split("(?!^)"); //-> ["a", "b", "c"]
This won't be dynamic. It will take O(n) + m to get to a character of a string. A much faster and dynamic approach would be a Hashmap where the key is the String and the value is a char array. Kind of unnecessarily complex but you get the seeking and individual letter charAts without having to go through the cumbersome process of resizing a primitive array.
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
- Split by
;to get rows. - Loop them, incrementing a counter (e.g.
x)- Split by
,to get values of each row. - Loop those values, incrementing a counter (e.g.
y)- Parse each value (e.g. using one of the
parseIntmethods ofInteger) and add it to thex,yof the array.
- Parse each value (e.g. using one of the
- Split by
That is a JSON string. There are a number of libraries that will do this for you.
- JSON in Java
- GSON
That looks like JSON data, and you should treat it as such.
Try a JSON parsing library for Java. I like GSON for its simplicity. Take a look at the Gson.fromJson() set of methods.
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).
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 }
}