write a c program to replace a substring by a new substring.

#include<stdio.h>
#define MAX_LENGTH 100
void main()
{
    char acInpString[MAX_LENGTH],acOrig[MAX_LENGTH],acReplace[MAX_LENGTH];
    char *pcInpStringPtr = acInpString;
    char *pcOrigPtr = acOrig;
    char *pcReplacePtr = acReplace;
    char *pPos;
    int  iRes = 0;
    int  iCount = 0;
    fflush(stdin);
    system("clear");

    /* gets the input string from user */
    printf("\n Enter String : - ");
    gets(acInpString);

    printf("\n Enter substring to be replaced\n");
    gets(acOrig);

    printf("\n Enter Substring to be placed \n");
    gets(acReplace);

    /* check if substring to be replaced is present in entered string by user */
    if(!(pPos=strstr(acInpString,acOrig)))
    {
    printf("\n SUBSTRING TO BE REPLACED NOT PRESENT IN GIVEN STRING \n");
    }
    else
    {
    char acTemp[MAX_LENGTH];
    strncpy(acTemp,pcInpStringPtr,pPos-pcInpStringPtr);
    sprintf(acTemp+(pPos-pcInpStringPtr), "%s%s", pcReplacePtr, pPos+strlen(pcOrigPtr));
    puts(acTemp);

  }
}

0 comments:

Post a Comment