在Android中将字符串转换为字符串数组

时间:2018-09-20 03:18:58

标签: java arrays

我有3个这样的字符串:

  1. ["state","in",["assigned", "partially_available"]]
  2. ["state","in",["confirmed", "waiting"]]
  3. ["state","in",["confirmed", "waiting", "assigned"]]

现在我想将每个字符串转换为2个数组,其中前2个元素是一个数组,其他元素是一个数组(例如:["state", "in"] ["asigned", "partially_available"])。有什么办法吗?非常感谢你!

2 个答案:

答案 0 :(得分:0)

String s = "[state,in,[assigned, partially_available]]";

s = s.substring(1,s.length()-1); // removes first and last square bracket
String[] sArr = s.split(",(?! )"); // split only the comma which is not followed by a space character

String[] newArr1 = {sArr[0],sArr[1]}; // first array containing ["state","in"]

String temp = sArr[2].substring(1,sArr[2].length()-1); // remove the square brackets from the inner array 

String[] newArr2 = {temp.split(",")[0],temp.split(",")[1]}; // second array containing ["asigned", "partially_available"]

答案 1 :(得分:0)

尝试一下。

公共类TestArray {

public static void main(String[] args) {

    String string = "[state,in,[assigned, partially_available]]";
    String[] tempstr = string.split("\\["); //remove "["
    String arrayFirstElement = tempstr[1].substring(0,tempstr[1].length()-1);
    String arraySecondElement = tempstr[2].substring(0, tempstr[2].length()-2);

    System.out.println("arrayFirstElement : " + arrayFirstElement);
    System.out.println("arraySecondElement : " + arraySecondElement);

    String[] strArray = new String[2];
    strArray[0] = arrayFirstElement;
    strArray[1] = arraySecondElement;
    System.out.println("strArray[0] : " + strArray[0] + " AND strArray[1] : " + strArray[1]);

}

}