views:

116

answers:

4

In Java, I have an array of integers. Is there a quick way to convert them to a string?

I.E. int[] x = new int[] {3,4,5} x toString() should yield "345"

+3  A: 
StringBuffer str =new StringBuffer();
for(int i:x){  
str.append(i);
}  

You need to read all once at least.

org.life.java
+6  A: 

Simplest performant approach is probably StringBuilder:

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

If you find yourself doing this in multiple places, you might want to look at Guava's Joiner class - although I don't believe you'll be able to use it for primitive arrays.

Jon Skeet
@Jon Skeet thanks for your answer, it's a very good approach.
didxga
@Jon Skeet Wow, I am lucky, I found that your answer to my question is just your 10000th answer in Stackoverflow,am i right? Congrats!
didxga
I have up-voted your answer. But just a curious? What is more costly (time consuming)? StringBuilder.append(int) or y = y*10 + x; ? I know the primitives will work only till the Integer.MAX_VALUE, but if we always have less than that result, then what would be better?
Ashish Patil
+1  A: 

Try with this - you have to import java.util.Arrays and then -

String temp = Arrays.toString( intArray ).replace(", ", "");
String finalStr = temp.substring(1, temp.length()-2);

Where intArray is your integer array.

Sachin Shanbhag
That yields "[3,4,5]", not "345"
Landei
@Landei - yeah saw that.. Try now. Have edited the answer now
Sachin Shanbhag
That's going to give "3 4 5" now instead of "345".
Jon Skeet
@Jon Skeet - Yep. Sorry, replace method is adding a space. Edited again. Thanks.
Sachin Shanbhag
@Sachin Shanbhag thanks, it's a tricky way.
didxga
@didxga - yes, its surely tricky and within two lines of code. Admit I got it from this link if you need more info - http://www.daniweb.com/forums/thread14183.html
Sachin Shanbhag
Personally I'd rather use my five lines of simple code than two lines of code which have already proved themselves relatively hard to get right :)
Jon Skeet
+2  A: 
   int[] x = new int[] {3,4,5};
   String s = java.util.Arrays.toString(x).replaceAll("[\\,\\[\\]\\ ]", "")
Landei