Strings have build-in functionality to concatenate together. Write a function in
ID: 3672562 • Letter: S
Question
Strings have build-in functionality to concatenate together. Write a function in C++ called append() that does concatenation for two char arrays (you will have to pass in a third char array that will hold the result). You will also need to pass in the lengths of each char array. You may not use strings for this part.
Sample main code:
char first[] = {'I', ' ', 'a', 'm', ' '};
char second[] = {'f', 'i', 'n', 'i', 's', 'h', 'e', 'd', ''};
char result[200];
append(first, 5, second, 9, result);
cout << result;
Example output for above:
I am finished
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
void append(char arr1[], int len1, char arr2[], int len2, char result[]) {
for (int i = 0; i < len1; i++) {
result[i] = arr1[i];
}
for (int i = 0; i < len2; i++) {
result[i + len1] = arr2[i];
}
}
int main() {
char first[] = { 'I', ' ', 'a', 'm', ' ' };
char second[] = { 'f', 'i', 'n', 'i', 's', 'h', 'e', 'd', '' };
char result[200];
append(first, 5, second, 9, result);
cout << result << endl;
return 0;
}