Insert character at a location in a string
C program to insert character at any desired location in a string.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
void insert(char str[MAX], char ch, int pos)
{
int i, len;
len = strlen(str);
if(pos<=0 || pos>len+1)
{
printf("\nInsertion can not be done at this position");
getch();
exit(0);
}
else
{
for(i=len-1;i>=pos-1;i--)
{
str[i+1] = str[i];
}
str[pos-1] = ch;
str[len+1] = '\0';
}
}
void main()
{
char str[MAX];
char ch;
int pos;
printf("Enter first string\t:");
gets(str);
printf("Enter the character to be inserted\t:");
scanf("%c",&ch);
printf("Enter the position at which it is to be inserted\t:");
scanf("%d",&pos);
insert(str, ch, pos);
printf("\nModified string\t:%s",str);
getch();
}
Output
Enter first string :welcome to cousecrux.com
Enter the character to be inserted :r
Enter the position at which it is to be inserted :15
Modified string :welcome to coursecrux.com