For small strings you can "worm" the char's over, index by index, from right to left, and that's ok.
But that's also inefficient - much like bubblesort, actually. Because the char's may need to move many spaces over to the right, and a naive algorithm will really slow things down.
A better algorithm would be:
get the length of the string to be added, a[1], make that length1.
get the length of the string (the char array) that's to be adjusted (a2[]), and make that length2
Now choose the index that is length2 - length1. Start there, and move that char in a2[] to a2[length2-1].
Continue moving char's until the index = (length2 - length1) - length1. That is, if a1[] is 100 char's long, and a2[] = 1,000 char's in length, then you want to start at index 1,000 , and continue until you get to index 900. (Just remember to -1 from these index numbers for zero based arrays)
This is a naive implementation. If you run it step by step, you'll see that the char's are moved over and over again. The move itself is fast, but with a long string, I'd use the better algorithm described above. I don't have an example of it to show.
Code:
/*edit_str.c Overwrites or inserts a string into an array of char, Adak
Status: ok
*/
#include <stdio.h>
#include <string.h>
int insert(void);
int overwrite(void);
char a1[] = { "When you spit, upon a star" }; //apologies to Disney :)
char a2[] = { "you wish," };
char a3[] = {"Now is the time for all good men to come to the aid of their country."};
char a4[] = {" and wise"};
int main(void) {
overwrite();
insert();
return 0;
}
int insert(void) {
int i, j, left, right, length3, length4;
length3 = strlen(a3);
length4 = strlen(a4);
left = 27; //where I want to insert the a2 string
for(j = length4 - 1; j > -1; j--) {
for(i = length3 - 2; i > left; i--) {
a3[i+1] = a3[i];
if(i < 0 || i > length3-1)
return 1;
} //the a4 string is fed into a3, from right to
++i; //left. Each inserted char is then moved to the
a3[i] = a4[j]; //right in a3, appropriately.
if(j < 0 || j > length4-1)
return 1;
}
printf("%s\n", a3);
i = getchar();
return 0;
}
int overwrite(void) {
int i, j, left, right, length1;
left = 5;
right = strlen(a2);
length1 = strlen(a1);
for(i = left, j = 0; j < right; i++) {
a1[i] = a2[j++];
if(i > length1-1)
return 1;
}
printf("%s\n", a1);
i = getchar();
return 0;
}