2

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?

0

4 Answers 4

6

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?

Sign up to request clarification or add additional context in comments.

1 Comment

a & b should always be same length although unknown, so yeah that works aslong as i set the length of c. Thanks, so simple :)
6

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.

7 Comments

That's from an external library.
@Mob the OP says he's already using it: "I'm using commons lang v3 if that's any help."
That does the wrong thing, if I understand the OP correctly, that concatenates each array and puts the concatenated strings in the slots of c, but as I understand the OP, (s)he wants to combine corresponding entries of the different arrays.
OP wants to join a[0] and b[0] not a[0], a[1].
Thanks for this, there's actually 8 arrays so this is definitely helpfull!
|
2
c = new String[a.length];
for (int i=0; i<a.length; i++)
{
  c[i] = a[i] + b[i];
}

Comments

2

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.