2017-05-18 51 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;) –

相關問題