Leo Leo - 2 months ago 6
Java Question

concantenating elements in an array to a string

I'm confused a bit. I couldn't find the answer anywhere ;(

I've got an String array:

String[] arr = ["1", "2", "3"];


then I convert it to a string by:

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


I expected to get the string
"123"
, but I got the string
"[1,2,3]"
instead.

How could I do it in java? I'm using Eclipse IDE

Answer

Use StringBuilder instead of StringBuffer, because it is faster than StringBuffer.

Sample code

String[] strArr = {"1", "2", "3"};
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < strArr.length; i++) {
   strBuilder.append(strArr[i]);
}
String newString = strBuilder.toString();

Here's why this is a better solution to using string concatenation: When you concatenate 2 strings, a new string object is created and character by character copy is performed.
Effectively meaning that the code complexity would be the order of the squared of the size of your array!

(1+2+3+ ... n which is the number of characters copied per iteration). StringBuilder would do the 'copying to a string' only once in this case reducing the complexity to O(n).