Write a C program to insert a sub-string in to
given main string from a given position.
SOURCE CODE:
/*Program to Inserting a Substring into Main String.*/
#include<stdio.h>
void main()
{
char str[50],substr[20],temp[50];
int i,j,pos,len=0;
clrscr();
printf("Enter string:\n");
gets(str);
printf("Enter substring:\n");
gets(substr);
printf("Enter the position where you want to insert:");
scanf("%d",&pos);
for(i=0;str[i]!='\0';i++)
len++;
if(pos>len)
printf("\nInsertion is not possible.");
else
{
for(i=pos,j=0;str[i]!='\0';i++,j++)
temp[j]=str[i];
temp[j]='\0';
for(i=pos,j=0;substr[j]!='\0';i++,j++)
str[i]=substr[j];
for(j=0;temp[j]!='\0';j++,i++)
str[i]=temp[j];
str[i]='\0';
printf("\nAfter Insertion the string is:\n");
puts(str);
}
}
OUTPUT:
Write a C program to delete n Characters from
a given position in a given string.
SOURCE CODE:
/*Program to delete n characters from a given position in a given string.*/
#include<stdio.h>
#include<conio.h>
void main()
{
char str[50],temp[50];
int n,pos,i,j,len=0;
clrscr();
printf("\nEnter string:\n");
gets(str);
printf("\nEnter number of characters to delete:\n");
scanf("%d",&n);
printf("\nEnter postion where you want to delete:\n");
scanf("%d",&pos);
for(i=0;str[i]!='\0';i++)
len++;
if((pos+n)>len)
printf("\nDeletion of characters not possible.");
else
{
for(i=pos,j=pos+n;str[i]!='\0';i++,j++)
str[i]=str[j];
str[i]='\0';
printf("\nAfter removing %d characters from %d position, string is:\n",n,pos);
puts(str);
}
}
OUTPUT:
Write a C program to replace a
character of string either from beginning or ending or at a specified location.
SOURCE CODE:
/*Program to replace a character of string either from beginning or ending or at a specified location.*/
#include<stdio.h>
#include<conio.h>
void main()
{
char str[50],ch;
int opt,pos,i,len=0;
clrscr();
printf("\nEnter string:\n");
gets(str);
printf("\nEnter a character to replace:\n");
ch=getche();
for(i=0;str[i]!='\0';i++)
len++;
printf("\nMenu:\n1.Beginning\n2.Ending\n3.Specified Location\n");
opt: printf("\nEnter option:\n");
scanf("%d",&opt);
switch(opt)
{
case 1:str[0]=ch;
break;
case 2:str[len-1]=ch;
break;
case 3:printf("\nEnter position:\n");
scanf("%d",&pos);
if(pos>len)
printf("\nReplacing not possible.");
else
str[pos]=ch;
break;
default:printf("\nWrong option.");
goto opt;
}
printf("\nAfter replacing character, String is:\n");
puts(str);
}
OUTPUT: