Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining multiple string arrays into one

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?

like image 759
Jixi Avatar asked May 11 '26 19:05

Jixi


2 Answers

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?

like image 199
Daniel Fischer Avatar answered May 14 '26 11:05

Daniel Fischer


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.

like image 24
Sergey Kalinichenko Avatar answered May 14 '26 10:05

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!