Replace a substring in a string.
Program to replace the given sub string from a string.
#include<stdio.h>
int main()
{
int ls,i,j,k,flag=0,olt,pos,lt;
char st[20],sub[20];
printf("Enter the string:");
scanf("%[^\n]",st );
printf("Enter the substring:");
scanf("%s",sub );
for(i=0;st[i]!='\0';i++);//to find the length of string
ls=i;
for(i=0;sub[i]!='\0';i++);//to find the length of string
olt=i;
if(olt<1||olt>ls)
{
printf("Not possible to replace\n" );
return 0;
}
for(i=0;i<ls;)
{
j=0;
while(st[i++]==sub[j++])
{
if(j==olt)
{
flag=1;
pos=i-olt;
break;
}
}
}
if(flag==1)
{
printf("Enter new substring:" );
scanf("%s",sub );
for(i=0;sub[i]!='\0';i++);
lt=i;
for(i=pos,j=0;j<lt;j++,i++)
{
if(j<olt)
st[i]=sub[j];
else
{
for(k=ls+1;k>i;k--)
st[k]=st[k-1];
st[ls+2]='\0';
ls+=2;
st[i]=sub[j];
}
}
while(j<olt)
{
j++;
for(k=i;st[k]!='\0';k++)
st[k]=st[k+1];
}
printf("The string is: %s \n",st );
}
else
printf("The substring not found\n" );
return 1;
}
OUTPUT
#include<stdio.h>
int main()
{
int ls,i,j,k,flag=0,olt,pos,lt;
char st[20],sub[20];
printf("Enter the string:");
scanf("%[^\n]",st );
printf("Enter the substring:");
scanf("%s",sub );
for(i=0;st[i]!='\0';i++);//to find the length of string
ls=i;
for(i=0;sub[i]!='\0';i++);//to find the length of string
olt=i;
if(olt<1||olt>ls)
{
printf("Not possible to replace\n" );
return 0;
}
for(i=0;i<ls;)
{
j=0;
while(st[i++]==sub[j++])
{
if(j==olt)
{
flag=1;
pos=i-olt;
break;
}
}
}
if(flag==1)
{
printf("Enter new substring:" );
scanf("%s",sub );
for(i=0;sub[i]!='\0';i++);
lt=i;
for(i=pos,j=0;j<lt;j++,i++)
{
if(j<olt)
st[i]=sub[j];
else
{
for(k=ls+1;k>i;k--)
st[k]=st[k-1];
st[ls+2]='\0';
ls+=2;
st[i]=sub[j];
}
}
while(j<olt)
{
j++;
for(k=i;st[k]!='\0';k++)
st[k]=st[k+1];
}
printf("The string is: %s \n",st );
}
else
printf("The substring not found\n" );
return 1;
}
OUTPUT
Comments
Post a Comment