Here is a C++ program to replace sub string with another string
SOURCE CODE OUTPUT
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char str[100],subst[20],repst[20];
int l,i,j=0,k,i1,lenght1,lenght2;
cout<<"Enter String : ";
cin.getline(str,100);
cout<<"Enter sub string to be replaced : ";
cin>>subst;
cout<<"Enter string : ";
cin>>repst;
lenght1=strlen(subst);
lenght2=strlen(repst);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==subst[j])
j++;
else if(str[i]!=subst[j])
j=0;
if(subst[j]=='\0')
{
i1=i-lenght1+1;
if(lenght1==lenght2)
{
for(k=i1,l=0;k<=i;k++,l++)
str[k]=repst[l];
}
else if(lenght1-lenght2>0)
{
for(k=i1,l=0;repst[l]!='\0';k++,l++)
str[k]=repst[l];
for(;str[k]!='\0';k++)
str[k]=str[k+lenght1-lenght2];
i=i1+lenght2-1;
}
else
{
for(k=strlen(str);k>i;k--)
str[k+lenght2-lenght1]=str[k];
for(k=i1,l=0;repst[l]!='\0';k++,l++)
str[k]=repst[l];
i=lenght2-lenght1;
}
j=0;
}
}
cout<<"After replacing : "<<str;
return 0;
}
#include<string.h>
using namespace std;
int main()
{
char str[100],subst[20],repst[20];
int l,i,j=0,k,i1,lenght1,lenght2;
cout<<"Enter String : ";
cin.getline(str,100);
cout<<"Enter sub string to be replaced : ";
cin>>subst;
cout<<"Enter string : ";
cin>>repst;
lenght1=strlen(subst);
lenght2=strlen(repst);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==subst[j])
j++;
else if(str[i]!=subst[j])
j=0;
if(subst[j]=='\0')
{
i1=i-lenght1+1;
if(lenght1==lenght2)
{
for(k=i1,l=0;k<=i;k++,l++)
str[k]=repst[l];
}
else if(lenght1-lenght2>0)
{
for(k=i1,l=0;repst[l]!='\0';k++,l++)
str[k]=repst[l];
for(;str[k]!='\0';k++)
str[k]=str[k+lenght1-lenght2];
i=i1+lenght2-1;
}
else
{
for(k=strlen(str);k>i;k--)
str[k+lenght2-lenght1]=str[k];
for(k=i1,l=0;repst[l]!='\0';k++,l++)
str[k]=repst[l];
i=lenght2-lenght1;
}
j=0;
}
}
cout<<"After replacing : "<<str;
return 0;
}
Any questions regarding to program please write in comments.
No comments:
Post a Comment