I want to insert a char* to a defined location in another char*. For example:
char str1[80] = "Hello world!";
char str2[] = "the ";
I want the result to be Hello the world!
(insert str2
to location 6
of str1
)
I have tried:
#include <stdio.h>
char str1[80] = "Hello world!";
char str2[] = "the ";
char tmp1[80];
char tmp2[80];
char *string_insert(char *scr, char *ins, int loc){
// Get the chars from location 0 -> loc
for(int i = 0; i <= loc; i++){
tmp1[i] = scr[i];
}
// Get the chars from loc -> end of the string
for(int i = 0; i < sizeof(scr) - loc; i++){
tmp2[i] = scr[i + loc];
}
// Insert the string ins
for(int i = 0; i < sizeof(ins); i++){
tmp1[i + loc] = ins[i];
}
// Add the rest of the original string
for(int i = 0; i < sizeof(scr) - loc; i++){
tmp1[loc + 1 + i] = tmp2[i];
}
return tmp1;
}
int main(){
printf("%s", string_insert(str1, str2, 6));
return 0;
}
But then I got Hello two
. You can execute it online at onlinegdb.com
I also wonder if there is any function from string.h
that can do this?
Thanks for any help!