Wednesday, March 14, 2012

C source code to insert string in another string.

Here I have a small code snipet, which i was developed for my personal purpose. This C code will insert a string in another string. I think many people could have these kinds of requirement in their regular work.


char *insert_new_string(int position, char *str_ptr1, char *str_ptr2)
{
char *new_str,*tmpstr;

new_str=(char *)malloc(strlen(str_ptr1)+strlen(str_ptr1)+6);
*new_str=NULL;
int string_count = 0; /* Counts the characters in the string */
tmpstr = new_str;

while (*str_ptr1 != '\0')
{
if (string_count == position)
{
while (*str_ptr2 != '\0')
{
*new_str=*str_ptr2;
new_str++;
str_ptr2++;
}

}
else
{
*new_str=*str_ptr1;
new_str++;
str_ptr1++;
}
string_count++;

}
new_str='\0';
new_str= tmpstr;
return new_str;

}


int main(int argc, char *argv[])
{
int pos=3;
char *str_var = " hi everybody";
char *new_str;

new_str= insert_new_string(pos,str_var,"new string" ); // insert new string

free(new_str);

return 0;
}

Please let me know, if you have any problem when executing this code.

No comments:

Post a Comment