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
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.
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.
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 .
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)
.
Simple answer:
Arrays.toString(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With