Q:

C program to insert substring into a string

0

C program to insert substring into a string

C program to insert a substring into a string: This code inserts a string into the source string. For example,if the source string is "C programming" and string to insert is " is amazing" (please note there is space at beginning) and if we insert string at position 14 then we obtain the string "C programming is amazing". In our C program we will make a function which performs the desired task and pass three arguments to it the source string, string to insert and position. You can insert the string at any valid position

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include 
#include 
#include 

void insert_substring(char*, char*, int);
char* substring(char*, int, int);

int main()
{
   char text[100], substring[100];
   int position;
   
   printf("Enter some text\n");
   gets(text);
   
   printf("Enter a string to insert\n");
   gets(substring);
   
   printf("Enter the position to insert\n");
   scanf("%d", &position);
   
   insert_substring(text, substring, position);
   
   printf("%s\n",text);
   
   return 0;
}

void insert_substring(char *a, char *b, int position)
{
   char *f, *e;
   int length;
   
   length = strlen(a);
   
   f = substring(a, 1, position - 1 );      
   e = substring(a, position, length-position+1);

   strcpy(a, "");
   strcat(a, f);
   free(f);
   strcat(a, b);
   strcat(a, e);
   free(e);
}

char *substring(char *string, int position, int length)
{
   char *pointer;
   int c;
 
   pointer = malloc(length+1);
   
   if( pointer == NULL )
       exit(EXIT_FAILURE);
 
   for( c = 0 ; c < length ; c++ )
      *(pointer+c) = *((string+position-1)+c);      
       
   *(pointer+c) = '\0';
 
   return pointer;
}

Output of program:

Enter some Text 

Computer is ammazing

Enter the string to insert

programming

Enter the position to insert

10

Computer programming is ammazing

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now