img
Question:
Published on: 21 November, 2024

Write a C-Program That Uses Functions To Insert A Sub-String In To A Given Main String From A Given Position.

Answer:
/* Declaring C-Libraries */ 
#include <stdio.h> 
#include <conio.h>

/* Declaring function prototypes */ 
void ins_substr(char [], char [], int, int);

/* main function is starting */ 
main()
{
     int p,n,i,j;
     char str[50],substr[50]; 
     clrscr();

     /* Initializing character array */ 
     puts("\n Enter the String:"); 
     gets(str);
     fflush(stdin);

     /* Entering the position where you want to insert a substring*/ 
     printf("Enter the specific position "); 
     scanf("%d",&p);

     printf("\n Enter the Number of Characters:"); 
     scanf("%d",&n);
     fflush(stdin);
     puts("\n Enter Sub-String:"); 
     gets(substr);

     /* function call to inserting string in main string */ 
     ins_substr(str,substr,p,n);
     printf("\n :: End of the main program ::"); 
     getch();
}

/* logic to insert sub string in main string */
void ins_substr(char str[], char substr[], int p, int n)
{
    int q,i,j; q=p-1;
    for(i=q,j=n;str[i]!='\0';i++,j++) 
       substr[j]=str[i];
    substr[j]='\0'; 
    for(j=0,i=q;substr[j]!='\0';j++,i++)
       str[i]=substr[j]; 
    str[i]='\0';
    printf("\n The string after inserting substring :"); 
    puts(str);
}

Random questions