Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating 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

like image 843
Leo Avatar asked Feb 19 '13 12:02

Leo


People also ask

How do you concatenate two elements in an array?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

Can you concatenate an array?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

How do you concatenate elements in an array in C++?

The recommended solution is to use the std::copy from the <algorithm> header to concatenate two arrays. The idea is to allocate memory large enough to store all values of both arrays, then copy the values into the new array with std::copy .


2 Answers

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

like image 161
Naveen Kumar Alone Avatar answered Oct 22 '22 00:10

Naveen Kumar Alone


Simple answer:

Arrays.toString(arr);

like image 16
Marco Avatar answered Oct 22 '22 02:10

Marco