替换字符串中的多个字符

Replacing more than one character in a String

我正在打印一个数组,但我只想显示数字。我想从 String 中删除括号和逗号(只保留数字)。到目前为止,我已经能够删除逗号,但我正在寻找一种向 replaceAll 方法添加更多参数的方法。

如何删除括号和逗号?

cubeToString = Arrays.deepToString(cube);
System.out.println(cubeToString); 
String cleanLine = "";
cleanLine = cubeToString.replaceAll(", ", ""); //I want to put all braces in this statement too
System.out.println(cleanLine);

输出为:

[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5]]
[[0000][1111][2222][3333][4444][5555]]

可以使用特殊字符[]组成一个模式,然后\转义[](来自你的输入)喜欢,

cleanLine = cubeToString.replaceAll("[\[\]\s,]", "");

替换数字以外的所有内容。喜欢,

cleanLine = cubeToString.replaceAll("\D", "");

您正在做的是像使用脚本语言一样有效地使用 Java。 在这种情况下,它恰好运行良好,因为您的数组只包含数字,您不必担心转义字符也可能出现在您的数组元素中。

但它仍然没有效率或 Java-喜欢多次转换字符串,其中一次使用正则表达式 (replaceAll),以获得最终结果。

更好、更有效的方法是直接构建您需要的字符串,而不使用任何逗号或方括号:

public static void main(String[] args) throws Exception {
    int[][] cube = { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 },
            { 5, 5, 5, 5 } };

    StringBuilder builder = new StringBuilder();
    for (int[] r : cube) {
        for (int c : r) {
            builder.append(c);
        }
    }
    String cleanLine = builder.toString();
    System.out.println(cleanLine);
}

输出:

000011112222333344445555