Prateek Mathur
Prateek Mathur

Reputation: 333

How to get rid of the braces and commas returned by Arrays.toString()?

Consider this code-

import java.util.Arrays;

class Test  {
public static void main(String args[])  {
    int[] arr=new int[5];

    for (int i=0; i<5; i++) {arr[i]=i;}

    String sarr=Arrays.toString(arr);
    System.out.println(sarr);
}
}

The output is-

[0, 1, 2, 3, 4]

I want to know weather there is a way to get rid of the braces and the commans introduced by toString()?? I want my String to be like this-

"01234"

Upvotes: 0

Views: 1705

Answers (5)

Reimeus
Reimeus

Reputation: 159754

You could remove all non digit characters:

String sarr = Arrays.toString(arr).toString().replaceAll("\\D+", "");

Upvotes: 1

koljaTM
koljaTM

Reputation: 10262

I would recommend not relying on the toString() representation from Arrays, since it is mostly meant for easier debugging, not for any productive use. If you want the information in a certain structured way, format it that way yourself (e.g. by looping over the array and appending to a StringBuilder).

Upvotes: 0

Mena
Mena

Reputation: 48404

You could use fast enumeration and StringBuilder - maybe into a static method taking int[] as argument.

For instance:

int[] arr = new int[] {0,1,2,3,4};
StringBuilder sb = new StringBuilder(arr.length);
for (int i: arr) {
    sb.append(i);
}
System.out.println(sb.toString());

Output:

01234

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500215

Just build the string yourself, with a StringBuilder:

StringBuilder builder = new StringBuilder();
for (int value : arr) {
    builder.append(value);
}
String text = builder.toString();

Basically if you don't want the formatting that Arrays.toString provides you, I'd avoid using it in the first place.

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

The best way to get rid of the characters that you do not want is to not put them in in the first place:

StringBuilder sb = new StringBuilder();
for (int n : arr) {
    sb.append(n);
}
String sarr = sb.toString();

However, if you must remove the punctuation after the fact, you could use replaceAll:

sarr = sarr.replaceAll("[^0-9]", "");

Upvotes: 3

Related Questions