Java多维数组转换为字符串和字符串转换为数组

5

我有一个数组

data[][];

转换为字符串:

string = Arrays.deepToString(data);

字符串:

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

并且如何将这个字符串转换回数组?

1
如何将什么转换为什么?data仍然是一个数组。 - Maroun
你不能这样做;对象和字符串表示之间没有双射。 - fge
@MarounMaroun 我假设原始数组不再可用。 - Pablo
如何将多维数组转换为字符串并再次转换为数组 - zix
我需要将数组转换成字符串通过https发送到服务器www(php文件),然后接收字符串并将其转换为数组。 - zix
4个回答

6
尝试使用我的stringToDeep()方法将其转换回数组。
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;
}
}

4

Java API中没有自动将此转换回数组的方法。您可以编写代码来自行完成此操作,但这可能会很棘手;此格式不会转义特殊字符,例如方括号或逗号。使用专为编码和解码数组设计的格式(例如JSON)可能更容易。


也许可以举个简单的例子? - zix
1
@zix 基本上答案是“不要这样做”。你正在发明自己的序列化数据方式,而不是使用标准方式,例如 JSON。 - Pablo
如何将字符串转换回数组? - JDGuide
int i = 0; int j = 0; String string = ""; for(j = 0; j<10; j++){ for(i = 0; i<10; i++){ string += data[j][i] + "#"; } string += "$$"; } - zix

1

我找到的所有答案都只适用于二维数组,所以这里是我针对任意维度反转 deepToString(...) 的解决方案:

使用示例:

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

这段代码将一个字符串 (arrString) 转换为数组,然后函数 Arrays.deepToString(...) 将其转换回相同的字符串。
函数代码:
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;
}

0

数组转字符串,再转回数组: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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接