concatenate two arrays into single dimensional array?
For example:-
Take two arrays
Array1[10] = {3,3,3}
Array2[10] ={3,2,1}
output
Array3[] = {33,32,31}
How will I get this output ?
concatenate two arrays into single dimensional array?
For example:-
Take two arrays
Array1[10] = {3,3,3}
Array2[10] ={3,2,1}
output
Array3[] = {33,32,31}
How will I get this output ?
Array1
and Array2
Integer.parseInt(String.valueOf(Array1[i])+String.valueOf(Array2[i]));
Array3
in the for-loop with the calculated valued.That's it.
int[] Array1 = new int[] {3,3,3};
int[] Array2 = new int[] {3,2,1};
int[] Array3 = new int[Array2.length];
for(int i = 0; i<Array1.length; i++) {
Array3[i] = Integer.parseInt(String.valueOf(Array1[i])+String.valueOf(Array2[i]));
}
Output:
Array3[] = {33,32,31}
This is not concatenating arrays, because that would look more like:
Array3[] = {3,3,3,3,2,1}
What you want to do is to concatenate each element inside the array, which is a different process entirely, and one you could accomplish with a simple for loop.
if(array1 is the same size as array2)
{
define array3 = new array[array1.length];
for(int x = 0 to array1.length)
{
array3[x] = array1[x] + array2[x].
}
}
This is pseudocode, which I provide when the question doesn't contain any code. It's up to you to figure out how to turn this into Java code, although that isn't too difficult. You'll also notice I'm using the +
operator for concatenation. I'm assuming your values are String
type. If they're not, then get creative, using the Integer.parseInt
method.
Quick hint: to concatenate two integer values simply use:
array3[i] = array1[i] + "" + array2[i];
The result will be transformed to Srting
because the second operand ""
is a String
.
try this:
for(int i = 0; i< Array1.length; i++)
{
Array3[i] = Integer.parseInt(String.format("{0}{1}", Array1[i],Array2[i]));
}