2017-05-18 42 views
-4

我有以下字符串:转换数组中的字符串格式到一个数组

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

什么是Java中最简单的方法将其转换为一个纯粹的多维float数组? 财产以后像这样的例子:

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 

当然,我可以写一个算法,将例如读取每个字符左右。但是也许有一种java已经提供的更简单快捷的方式。

+1

请仔细阅读[我如何问一个好问题?](http:/ /stackoverflow.com/help/how-to-ask),然后再尝试提出更多问题。 –

+1

在尝试提出更多问题之前,请阅读[应避免询问什么类型的问题?](http://stackoverflow.com/help/dont-ask)。 –

+0

为什么不在实际的字符串数组中传递“stringArray”? – XtremeBaumer

回答

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

从我的脑海顶部的“伪”:

1-摆脱第一和最后一个字符(例如:删除第一个“[”和最后一个“]”)。使用regex找到括号内的文字。

3-在步骤2和split的匹配项上循环“,”字符。

4-在拆分字符串上循环并修剪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;) –

相关问题