zix
zix

Reputation: 53

Java multidimensional Array to string and String to Array

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?

Upvotes: 5

Views: 3167

Answers (4)

potato
potato

Reputation: 1123

All the answers I found are 2-dimensional only, so here's my solution to reverse deepToString(...) for any number of dimensions:

Usage example:

String arrString = "[[[0.11695497071135137, 0.8830064157596283, 0.3433854446148375, 0.18825445694298526, 1.0441938749175883, 0.8941633746325311], [-0.089908138214512, 0.39821330927870574, 0.1365997500579524, 0.7008902956765364, 0.9897596683277262, 0.2847717055995359], [0.6450670283688857, 0.01516064860567864, -0.07904927386204857, 0.2703900981351612, 0.45402985012492075, 0.30505608337251183], [0.5122943117220898, 0.008726346575469023, 0.7734611917871235, 0.3051772999891666, 0.5237487372571624, 1.1824105144656751]]]";
String[][][] arr = (String[][][]) reverseDeepToString(arrString);
System.out.println(Arrays.deepToString(arr));

This code converts a string (arrString) into an array, and then the function Arrays.deepToString(...) converts it back into the same string.

Function code:

public static Object reverseDeepToString(String str){
    int dimensions = 0;
    for(int x = 0; x < str.length(); x++)
        if(str.charAt(x) == '[')
            dimensions++;
        else break;
    str = str.substring(dimensions, str.length() - dimensions);
    return createArrayRecursive(str, dimensions);
}

private static Object createArrayRecursive(String str, int dimension){
    
    if(dimension == 1)
        return str.split(", "); // modify the code here if you want to convert the strings to another variable type
    
    String[] s = str.split(getArraySeparator(dimension));
    int[] lengths = new int[dimension];
    lengths[0] = s.length;
    Object arr = Array.newInstance(String.class, lengths); // and here (see comment above)
    
    for(int x = 0; x < s.length; x++)
        Array.set(arr, x, createArrayRecursive(s[x], dimension - 1));
    
    return arr;
}

private static String getArraySeparator(int dimension){
    String separator = ", ";
    for(int x = 1; x < dimension; x++)
        separator = ']' + separator + "\\[";
    return separator;
}

Upvotes: 1

Akhilesh Dhar Dubey
Akhilesh Dhar Dubey

Reputation: 2148

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;
}
}

Upvotes: 6

zix
zix

Reputation: 53

Array to string and back to array :P

import java.util.Arrays;
import java.util.Random;

public class arrays {

    public static void main(String [ ] args)
    {
        String[][] in = new String [10][4];
        String[][] out = new String [10][4];
        arrays nr = new arrays();

        for(int i =0; i< 4; i++){
            for(int j =0; j< 4; j++){
                in[i][j] = nr.Rand(5);
            }       
        }
        System.out.println(Arrays.deepToString(in));

        // tablica ok
        // convert array to string
        String line = "";
        for(int i =0; i< 4; i++){
            for(int j =0; j< 4; j++){
                line += in[i][j] + "_";
            }       
            line += ":";
        }

        System.out.println(line);

        // line back to array

         String[] xline = line.split(":");

         int ss = 0;
         for (String str : xline) {
             out[ss] = (String[]) str.split("_");

              System.out.println("string line>>>" + str);

              ss++;
         }

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

      public String nextSessionId() {
          //private SecureRandom random = new SecureRandom();
          //return new BigInteger(130, random).toString(32);
          return null;
      }

      public String Rand(int zz){
          char[] chars = "987654321abcdefghijklm111nopqrstuvwxyz0123456789".toCharArray();
          StringBuilder sb = new StringBuilder();
          Random random = new Random();
          for (int i = 0; i < zz; i++) {
              char c = chars[random.nextInt(chars.length)];
              sb.append(c);
          }
          String output = sb.toString();
          //    System.out.println(output);
          return output;

      }
}

:D

Upvotes: 0

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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.

Upvotes: 4

Related Questions