1

I have two arrays:

String[] ArrayA = {"9","1","4","2","3"}; 
String[] ArrayB = {"9","2","8"};

How do I get a new array like the following

String[] ArrayC = {"9","2","8","A","A"};

The logic is to create a new ArrayC of length equal to ArrayA and backfill the remaining array elements (ArrayA length minus ArrayB length = 2) difference with "A".

2
  • 1
    You'll need to know how to create arrays and write loops. That's all we can help with, without knowing what you've already tried. Commented Aug 14, 2015 at 12:04
  • Please share your code. Commented Aug 14, 2015 at 12:04

3 Answers 3

6

Read the javadoc of Arrays.

arrayC = Arrays.copyOf(arrayB, arrayA.length);
Arrays.fill(arrayC, arrayB.length, arrayA.length, "A");
Sign up to request clarification or add additional context in comments.

2 Comments

@Downvoter: Would you care to explain? This looks like a perfectly fine answer to me.
I can understand the down-vote: no explanation. Though intentionally just a javadoc link. Reasons: (1) no own effort in question (2) just might be some homework.
0

You could just iterate over arrayB and copy it:

String[] arrayA = {"9","1","4","2","3"}; 
String[] arrayB = {"9","2","8"};
String[] arrayC = new String[arrayA.length];

// copy arrayB:
for (int i = 0; i < arrayB.length; ++i) {
    arrayC[i] = arrayB[i];
} 

// fill in the remainder:
for (int i = arrayB.length; i < arrayA.length; ++i) {
    arrayC[i] = "A";
} 

1 Comment

Why not rely on API functions for this kind of things?
0

Based on the previous posted code,this is a generic method which satisfy your need, it takes 3 params , two arrays and the word to be used to be used in replacing empty elements

public static String [] fill(String [] arrayA, String[] arrayB ,String word) {
String[] toBeCopied = null ;
   int size ;
if( arrayA.length > arrayB.length ) {
    size = arrayA.length ;
    toBeCopied = arrayB ;
} else {
    size = arrayB.length ;
    toBeCopied = arrayA ;
}
String[] arrayC = new String[size];
for (int i = 0; i < toBeCopied.length; ++i) {
    arrayC[i] = toBeCopied[i];
}
for (int i=toBeCopied.length;i<arrayC.length ;i++ )
    arrayC[i] = word;
   return arrayC ;

}

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.