Insert sub-string at a position
C program to insert a sub-string in to given main string at a given position.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
void insert(char str1[MAX], char str2[MAX], int pos)
{
int i, j, len1, len2;
len1 = strlen(str1);
len2 = strlen(str2);
if(pos<=0 || pos>len1+1)
{
printf("\nInsertion can not be done at this position");
getch();
exit(0);
}
else
{
for(i=0;i<len2;i++)
{
for(j=len1-1+i;j>=pos-1+i;j--)
{
str1[j+1] = str1[j];
}
}
j = pos-1;
for(i=0;i<len2;i++)
{
str1[j] = str2[i];
j++;
}
str1[len1+len2] = '\0';
}
}
void main()
{
char str1[MAX], str2[MAX];
char ch;
int pos;
printf("Enter the main string\t:");
gets(str1);
printf("Enter the substring to be inserted\t:");
gets(str2);
printf("Enter the position at which it is to be inserted\t:");
scanf("%d",&pos);
insert(str1, str2, pos);
printf("\nModified string\t:%s",str1);
getch();
}
Output
Enter the main string :welcome to course.com
Enter the substring to be inserted :crux
Enter the position at which it is to be inserted :18
Modified string :welcome to coursecrux.com