Sunday, 12 February 2023

C Program to Delete and Replace Words form a String (Note: Give space too if you want to delete or replace a single character with no letter around it)



#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<ctype.h>


//using namespace std;  //Don't use this line because it is only useful for C++ programs 

int main()

{

    char n[50],m[50],o[50],ans;

    int i,j,k,ln,lm,lo,l;

//  clrscr();      //use this line in TurboC++ to clear console

    printf("\n enter your sentence: ");

    fflush(stdin);       // this function is used for clear standard input stream so garbage don't interrupt our programe 

    gets(n);          //this is function to take input string until enter is pressed

Dragon:    //this word is used to give a check point to our programe you can also use do...while() instead of this line

    printf("\n press d to delete or r to replace any string you want and x to exit program: ");

    fflush(stdin);

    ans=tolower(getchar());          //use getchar to take character input

if(ans=='d'||ans=='D')

    printf("\n Enter word you want to delete: ");

else if(ans=='r'||ans=='R')

    printf("\n Enter word you want to replace: ");

    else if(ans=='x'||ans=='X'){

    printf("\n Exiting Program............... ");

        return 0;

    }

    else{

    printf("\n Please chose one option: ");

    goto Dragon;                       //goto is used to get to the check point

    }

    fflush(stdin);

    gets(m);

    for(i=0;n[i]!='\0';i++)

    {

if(n[i]==m[0])

{

    for(k=i,j=0;m[j]!='\0';j++,k++)

if(n[k]!=m[j])

    break;

    if(m[j]=='\0')

    {

            if(ans=='d')

            {

                if(isspace(n[k]))

                k++;

                for(j=i;n[k]!='\0';j++,k++)

                n[j]=n[k];

                n[j]='\0';

            }

            else

            {

                printf("\n enter new word to replace with: ");

                fflush(stdin);

                gets(o);

                lo=strlen(o);

                for(j=i;n[k]!='\0';j++,k++)

                n[j]=n[k];

                n[j]='\0';

                for(ln=strlen(n);ln>=i;ln--)

                n[ln+lo]=n[ln];

                for(j=0,k=i;o[j]!='\0';k++,j++)

                n[k]=o[j];

            }

    }

}

    }

    printf("\n yor new sentence: %s",n);

    //getch();                     //use getch() function in TurboC++ to hold console


    return 0;

}


 

No comments:

Post a Comment