Replacing more than one character in a String

655 Views Asked by At

I am printing an array, but I only want to display the numbers. I want to remove the brackets and commas from the String (leaving only the digits). So far, I have been able to remove the commas but I was looking for a way add more arguments to the replaceAll method.

How can I remove the brackets as well as the commas?

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);

The output is:

[[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]]
2

There are 2 best solutions below

2
On BEST ANSWER

You can use the special characters [ and ] to form a pattern, and then \\ to escape the [ and ] (from your input) like,

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

or replace everything not a digit. Like,

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

What you are doing is effectively using Java like you use a scripting language. In this case, it happens to work well because your arrays only contain numbers and you don't have to worry about escaping characters that may also appear inside your array elements.

But it's still not efficient or Java-like to be converting strings several times, one of them with regular expressions (replaceAll), to get to your end-result.

A nicer and more efficient approach is to directly build the string that you need without any comma's or square brackets:

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);
}

Output:

000011112222333344445555