Find a sub string in a given string and replace it with another string.
Solution:
#include<stdio.h>
#include<string.h>
int main(){
char str[100],substr[100],replacestr[100];
int i,j,k;
gets(str);
gets(substr);
gets(replacestr);
if(strlen(str)>strlen(substr)){
for(i=0;str[i]!='\0';i++){
k=i;
//Find substring(substr) in the given original string(str)
for(j=0;substr[j]!='\0';j++,k++){
if(str[k]!=substr[j])
break;
}
//Substring(substr) is found replace it with another string(replacestr)
if(substr[j]=='\0'){
//Replace string when length of substring is greater than or equal to length of replace string
if(strlen(substr)>=strlen(replacestr)){
for(j=0;replacestr[j]!='\0';j++,i++)
str[i]=replacestr[j];
j--;
for(k=i;j<strlen(substr)-1;k++,j++)
str[k]=str[k+1];
}
//Replace string when length of substring is less than length of replace string
else{
while(j<=strlen(replacestr)-1){
for(k=strlen(str);k>=i;k--)
str[k+1]=str[k];
j++;
}
for(j=0;replacestr[j]!='\0';j++,i++)
str[i]=replacestr[j];
}
}
}
}
puts(str);
}
Solution:
#include<stdio.h>
#include<string.h>
int main(){
char str[100],substr[100],replacestr[100];
int i,j,k;
gets(str);
gets(substr);
gets(replacestr);
if(strlen(str)>strlen(substr)){
for(i=0;str[i]!='\0';i++){
k=i;
//Find substring(substr) in the given original string(str)
for(j=0;substr[j]!='\0';j++,k++){
if(str[k]!=substr[j])
break;
}
//Substring(substr) is found replace it with another string(replacestr)
if(substr[j]=='\0'){
//Replace string when length of substring is greater than or equal to length of replace string
if(strlen(substr)>=strlen(replacestr)){
for(j=0;replacestr[j]!='\0';j++,i++)
str[i]=replacestr[j];
j--;
for(k=i;j<strlen(substr)-1;k++,j++)
str[k]=str[k+1];
}
//Replace string when length of substring is less than length of replace string
else{
while(j<=strlen(replacestr)-1){
for(k=strlen(str);k>=i;k--)
str[k+1]=str[k];
j++;
}
for(j=0;replacestr[j]!='\0';j++,i++)
str[i]=replacestr[j];
}
}
}
}
puts(str);
}
Sample Input1:
lazy girl
girl
boy
Sample Output1:
lazy boy
Sample Input2:
lazy boy
boy
girl
Sample Output2:
lazy girl