Sunday, February 14, 2010

Write a c Program to Replace a Substring by a New Substring.

fnReplaceString()
{
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 */
GET_STRING(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);

}
}

No comments: