Reputation: 117
Basically I have multiple string arrays and I want to combine them.
Not just extend the first array but combine a[0]
and b[0]
into single line.
like so:
String[] a = {"line1", "line2"};
String[] b = {"line3", "line4"};
String[] c;
Combine code here
c[0] == "line1line3";
c[1] == "line2line4";
I'm using commons lang v3 if that's any help.
I can combine the 2 arrays with
c = (String[]) ArrayUtils.addAll(a, b);
But that's just makes c = "line1", "line2", "line3", "line4"
Anyone ever done this?
Upvotes: 2
Views: 5198
Reputation: 726579
You can use StringUtils.join
from commons lang to "glue" the strings together:
for (int i = 0 ; i != c.length ; i++) {
c[i] = StrungUtils.join(a[i], b[i]);
}
This might be a bit faster in case that you need to join more than two arrays, but in case of just two arrays it will almost certainly be slower.
Upvotes: 6
Reputation: 1229
you'll have to add handling of invalid indices, but here you go:
String[] c = new String[len];
for( int i = 0; i < len; i++ ){
c[i] = a[i] + b[i];
}
Upvotes: 2
Reputation: 4156
c = new String[a.length];
for (int i=0; i<a.length; i++)
{
c[i] = a[i] + b[i];
}
Upvotes: 2
Reputation: 183888
If the arrays have the same length, what about
for(int i = 0; i < a.length; ++i){
c[i] = a[i] + b[i];
}
just concatenating corresponding strings in a loop?
Upvotes: 6