In this post under Java. I will show with example how to merge two character arrays into one.
Below is the complete code for your reference.
Main Class
1 package core.string;
2
3 public class Example1 {
4 public static void main(String[] args) {
5 char[] inputArray1 = {'a', 'b', 'c'};
6 char[] inputArray2 = {'d', 'e', 'f'};
7
8 StringBuilder stringBuilder = new StringBuilder();
9 stringBuilder.append(inputArray1);
10 stringBuilder.append(inputArray2);
11 char[] outputArray = new char[inputArray1.length + inputArray2.length];
12 stringBuilder.getChars(0, stringBuilder.length(), outputArray, 0);
13 for(char ch : outputArray) {
14 System.out.print(ch);
15 }
16 }
17}
In the above code, at line 5 and 6, we declare two character arrays “inputArray1” and “inputArray2”.
At line 8, create a new “StringBuilder” object named “stringBuilder”
At line 9, we append the “inputArray1” elements to “stringBuilder” by calling “append” method and passing the “inputArray1” as an argument. At line 10 we repeat the previous step for “inputArray2” array.
At line 11, we create a new character array named “outputArray” whose length is equal to sum of “inputArray1” and “inputArray2” length.
At line 12, we use “getChars” instance method of “stringBuilder” instance to copy the characters present in StringBuilder object to destination array “outputArray”.
The first parameter to “getChars” is an integer and it indicates the starting index in the StringBuilder from where we need to read the characters for the purpose of copying it.
The second parameter is also an integer and indicates the ending index in the StringBuilder till where we need to read the characters for the purpose of copying it.
The third parameter is the destination character array to which data has to be copied
The fourth parameter is also an integer and indicates the starting index present in “outputArray” to start placing the copied characters.
In this way we can merge two character arrays.