java将这个字符串转换成字符串数组的最佳方法是什么?
我正在实现一个游戏服务器,并将游戏板表示为一个字符串,以这个状态为例:
String b = ", a36, a32, a26, a40, a295, a41, a49, /, , a16, a09, a68, a11, a99, ,"
我想将此字符串转换为以下字符串数组:
[, a36, a32, a26, a40, a295, a41, a49, , , , a16, a09, a68, a11, a99, ]
我试着使用String.split
:
String[] bArray = b.split("/|,");
这将产生:
boardArray = [, a36, a32, a26, a40, a295, a41, a49, , , , a16, a09, a68, a11, a99]
它切断了数组中我想要的最后一个" "
元素。修改代码并手动添加最后一个元素后:
String[] bArray = b.split("/|,");
bArray = Arrays.copyOf(bArray, bArray.length + 1);
bArray[bArray.length - 1] = "";
这给了我正确的结果,但这个解决方案效率低下。有人知道如何更干净地做这件事吗
# 1 楼答案
试试这个:
这与极限参数(第二个)分开,正如documenation所说:
# 2 楼答案
尝试加载到
List<String>
并遍历该列表输出: