Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java multidimensional Array to string and String to Array

Tags:

java

arrays

swing

I have array

data[][];

convert to string:

string = Arrays.deepToString(data);

string:

[[1, 1394119227787, 59474093, USD/DKK, true, 0.05, 5.391582, 5.00663, 5.39663, null, null], [1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null]]

and How convert this string back to array?

like image 463
zix Avatar asked Mar 13 '14 11:03

zix


2 Answers

Try my stringToDeep() method to convert back to Array.

import java.util.*;

public class DeepToArray {

public static void main(String[] args) {

    int row, col;
    row = 2;
    col = 3;
    String[][] in = new String[row][col];

    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            in[i][j] = i + " " + j;
        }
    }
    String str = Arrays.deepToString(in);

    System.out.println(str);

    String[][] out = stringToDeep(str);

    for (String s2[] : out) {
        for (String s3 : s2) {
            System.out.print(s3 + "  ");
        }
        System.out.println();
    }
}

private static String[][] stringToDeep(String str) {
    int row = 0;
    int col = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == '[') {
            row++;
        }
    }
    row--;
    for (int i = 0;; i++) {
        if (str.charAt(i) == ',') {
            col++;
        }
        if (str.charAt(i) == ']') {
            break;
        }
    }
    col++;

    String[][] out = new String[row][col];

    str = str.replaceAll("\\[", "").replaceAll("\\]", "");

    String[] s1 = str.split(", ");

    int j = -1;
    for (int i = 0; i < s1.length; i++) {
        if (i % col == 0) {
            j++;
        }
        out[j][i % col] = s1[i];
        //System.out.println(s1[i] + "\t" + j + "\t" + i % col);
    }
    return out;
}
}
like image 123
Akhilesh Dhar Dubey Avatar answered Nov 15 '22 03:11

Akhilesh Dhar Dubey


There is no method in the java API that will automatically convert this back to an array. You could write code to do this yourself, but it would be tricky; this format does not escape special characters like the square brackets, or the commas. It might be easier just to use a format which is designed for encoding and decoding arrays, like JSON.

like image 20
Ernest Friedman-Hill Avatar answered Nov 15 '22 05:11

Ernest Friedman-Hill