You are here

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.

C programming code

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. void insert_substring(char*, char*, int);
  6. char* substring(char*, int, int);
  7.  
  8. int main()
  9. {
  10.    char text[100], substring[100];
  11.    int position;
  12.    
  13.    printf("Enter some text\n");
  14.    gets(text);
  15.    
  16.    printf("Enter a string to insert\n");
  17.    gets(substring);
  18.    
  19.    printf("Enter the position to insert\n");
  20.    scanf("%d", &position);
  21.    
  22.    insert_substring(text, substring, position);
  23.    
  24.    printf("%s\n",text);
  25.    
  26.    return 0;
  27. }
  28.  
  29. void insert_substring(char *a, char *b, int position)
  30. {
  31.    char *f, *e;
  32.    int length;
  33.    
  34.    length = strlen(a);
  35.    
  36.    f = substring(a, 1, position - 1 );      
  37.    e = substring(a, position, length-position+1);
  38.  
  39.    strcpy(a, "");
  40.    strcat(a, f);
  41.    free(f);
  42.    strcat(a, b);
  43.    strcat(a, e);
  44.    free(e);
  45. }
  46.  
  47. char *substring(char *string, int position, int length)
  48. {
  49.    char *pointer;
  50.    int c;
  51.  
  52.    pointer = malloc(length+1);
  53.    
  54.    if( pointer == NULL )
  55.        exit(EXIT_FAILURE);
  56.  
  57.    for( c = 0 ; c < length ; c++ )
  58.       *(pointer+c) = *((string+position-1)+c);      
  59.        
  60.    *(pointer+c) = '\0';
  61.  
  62.    return pointer;
  63. }

Download Insert substring program.

Output of program:
Insert substring c program