将字符串格式的数组转换为数组

时间:2017-05-18 14:18:29

标签: java arrays

我有以下字符串:

"[[0, 0, 0], [1, 1, 1], [2, 2, 2]]"

将Java转换为纯多维浮点数组的最简单方法是什么? 比如这样的东西:

String stringArray = "[[0, 0, 0], [1, 1, 1], [2, 2, 2]]";
float[][] floatArray = stringArray.parseSomeHow() //here I don't know the best way to convert

当然,我可以编写一个算法来读取每个char左右的算法。但也许java已经提供了一种更简单,更快捷的方式。

2 个答案:

答案 0 :(得分:2)

我心目中的“伪代码”:

1-摆脱第一个和最后一个字符(例如:删除第一个“[”和最后一个“]”)。

2-使用regex查找括号内的文字。

3-循环执行步骤2的匹配,并使用“,”字符循环split

4-遍历拆分的String并修剪casting it into a float之前的值,然后将该值放入数组中的正确位置。

代码示例

public static void main(String[] args) {
    String stringArray = "[[0, 0, 0], [1, 1, 1], [2, 2, 2]]";

    //1. Get rid of the first and last characters (e.g: remove the first "[" and the last "]").

    stringArray = stringArray.substring(1, stringArray.length() - 1);

    //2. Use regex to find the text between brackets.
    Pattern pattern = Pattern.compile("\\[(.*?)\\]");
    Matcher matcher = pattern.matcher(stringArray);

    //3. Loop over the matches of step 2 and split them by the "," character.
    //4.  Loop over the splitted String and trim the value before casting it into a float and then put that value in the array in the correct position.

    float[][] floatArray = new float[3][3];
    int i = 0;
    int j = 0;
    while (matcher.find()){
        String group = matcher.group(1);
        String[] splitGroup = group.split(",");
        for (String s : splitGroup){
            floatArray[i][j] = Float.valueOf(s.trim());
            j++;
        }
        j = 0;
        i++;
    }
    System.out.println(Arrays.deepToString(floatArray));
   //This prints out [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]
}

答案 1 :(得分:1)

以下是实现它的一种方法:

public static float[][] toFloatArray(String s){
    String [] array = s.replaceAll("[\\[ ]+", "").split("],");

    float [][] floatArray = new float[array.length][];

    for(int i = 0; i < array.length; i++){
        String [] row = array[i].split("\\D+");
        floatArray[i] = new float[row.length];
        for(int j = 0; j < row.length; j++){
            floatArray[i][j] = Float.valueOf(row[j]);
        }           
    }

    return floatArray;
}

使用Java 8 Streams,这是另一种方法:

public static Float[][] toFloatArray2(String s) {
    return Pattern.compile("[\\[\\]]+[,]?")
            .splitAsStream(s)
            .filter(x -> !x.trim().isEmpty())
            .map(row -> Pattern.compile("\\D+")
                        .splitAsStream(row)
                        .map(r -> Float.valueOf(r.trim()))
                        .toArray(Float[]::new)
            )
            .toArray(Float[][]::new);
}
相关问题