Thursday, July 26, 2012

Insert a substring in a string

C program to insert substring into a string: This code inserts the target string into the source string.

For example if the source string is "c programming" and target string is " is amazing" (please note there is space at beginning) and if we add target string to source string at position 14 then we obtain the string "c programming is amazing". In our c code we will make a function which perform the desired task and we pass three arguments to it the source string, target string and position. You can insert the string at any valid position.

#include <string.h>
#include <stdlib.h>
#include <iostream>

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

   char text[100], substring[100];
   int position;

   printf("Enter some text\n");

   printf("Enter the string to insert\n");

   printf("Enter the position to insert\n");
   scanf("%d", &position);

   insert_substring(text, substring, position);


   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);
   strcat(a, b);
   strcat(a, e);

char *substring(char *string, int position, int length)
   char *pointer;
   int c;

   pointer =(char*) malloc(length+1);

   if( pointer == NULL )

   for( c = 0 ; c < length ; c++ )
      *(pointer+c) = *((string+position-1)+c);      

   *(pointer+c) = '\0';

   return pointer;

No comments:

Post a Comment