有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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] = "";

这给了我正确的结果,但这个解决方案效率低下。有人知道如何更干净地做这件事吗


共 (2) 个答案

  1. # 1 楼答案

    试试这个:

    b.split("/|,", -1);
    

    这与极限参数(第二个)分开,正如documenation所说:

    The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

  2. # 2 楼答案

    尝试加载到List<String>并遍历该列表

    String b = ", a36, a32, a26, a40, a295, a41, a49, /, , a16, a09, a68, a11, a99, ,";
    List<String> myList = Arrays.asList(b.split(","));
    System.out.println(myList);
    

    输出:

    [,  a36,  a32,  a26,  a40,  a295,  a41,  a49,  /,  ,  a16,  a09,  a68,  a11,  a99,  ]