我有2个String变量,
String expectedDocsTextReqA = "A1:A2:A3:A4";
String expectedDocsTextReqB = "B1:B2:B3:B4";
我想Split these 2 strings and store it in a single String array
如何做到这一点?
我正在努力实现这样的目标,但这会引发异常。有没有其他方法可以做到这一点?
String[] arr = expectedDocsTextReqA.split(":") + expectedDocsTextReqB.split(":");
答案 0 :(得分:0)
使用Split方法时,会创建一个无法调整大小的字符串数组。解决方案是将您的字符串数组转换为字符串列表:
String expectedDocsTextReqA = "A1:A2:A3:A4";
String expectedDocsTextReqB = "B1:B2:B3:B4";
List<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(expectedDocsTextReqA.split(":")));
list.addAll(Arrays.asList(expectedDocsTextReqB.split(":")));
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
答案 1 :(得分:0)
可能不是最有效的方法来做这样的事情,但是这里有。
String[] split1 = expectedDocsTextReqA.split(":");
String[] split2 = expectedDocsTextReqB.split(":");
//initialize result array size.
String[] result = new String[split1.length + split2.length];
int index = 0;
for (int i = 0; i < split1.length; i++) { //add elements of the first array
result[index] = split1[i]
index++;
}
for (int i = 0; i < split2.length; i++) { //add elements of the second array
result[index] = split2[i]
index++;
}
编辑:Joris的List实现可能是解决此问题的更合理的方法。