Write a C program to find a string within a sentence and replace it with another string.

Program Code:
#include <stdio.h>
int main()
{
char str1[50], str2[50], str3[50], temp[50];
int len1, len2, len3, i, j, p, match, k;
printf("\n\n\t ENTER A SENTENCE:");
gets(str1);
printf("\n\n\t ENTER A STRING WHICH YOU WANT TO DELETE: ");
gets(str2);
printf("\n\n\t ENTER A NEW STRING WHICH YOU WANT TO INSERT: ");
gets(str3);
i=0; //Finding the length of sentence
while(str1[i]!='\0')
{

i++;
}
len1 = i-1;
i=0; //Finding the length of string, to delete
while(str2[i]!='\0')
{
i++;
}
len2 = i-1;
i=0; //Finding the length of new string, to replace
while(str3[i]!='\0')
{
i++;
}
len3 = i-1;
for(i=0;i<=len1;i++)
{
match = 1;
for(j=0;j<=len2;j++)
{
if(str2[j]!=str1[i+j])
{
match = 0;
break;
}
}

if(match){ //When a substring is found, copy remaining String to temporary String
for(k=0,j=i+len2+1;j<=len1;j++,k++){
temp[k] = str1[j];
}
temp[k] = '\0';
for(j=0;j<=len3;j++)
{
str1[i+j] = str3[j];
}
str1[i+j] = '\0';
for(p=0;temp[p]!='\0';p++)
{
str1[i+j+p]=temp[p];
}
str1[i+j+p]='\0';
len1 = len1-len2 +len3; //Update length value
i = i + j;
}
}
printf("\n\n\t OUTPUT IS : ");
puts(str1);
}
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: