Do you like that?
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *ReplaceStrInsideString(char *ptrStr, const char *replaceStr, const char *insertStr)
{
if(!ptrStr || !insertStr)
{
fprintf(stderr,"NULL input strings.\n");
return NULL;
}
else
{
char *nptr = NULL;
if((nptr = strstr(ptrStr, replaceStr)) == NULL)
{
fprintf(stderr, "Can not find \"%s\" string inside \"%s\ string.\n", replaceStr, ptrStr);
return NULL;
}
else
{
/* Compute final length. */
int nEndLen, nReplaceStartIndex;
/* Save the lengths that are needed. */
int nInsertLen = strlen(insertStr);
int nReplaceLen = strlen(replaceStr);
int nInitLen = strlen(ptrStr);
/* Final length of the string is known. */
int nFinalLen = nInitLen - nReplaceLen + nInsertLen + 1;
/* Pointers to strings. */
char *nFinalStr = NULL;
char *nEndStr = NULL;
if((nFinalStr = calloc(nFinalLen, sizeof(char))) == NULL)
{
fprintf(stderr, "Memory Allocation Error.\n");
return NULL;
}
/* Where is the replace string? */
nReplaceStartIndex = nptr - ptrStr;
if(nReplaceStartIndex < 0)
nReplaceStartIndex = -nReplaceStartIndex;
nEndLen = nInitLen - nReplaceStartIndex + nReplaceLen+1;
if((nEndStr = calloc(nEndLen, sizeof(char))) == NULL)
{
fprintf(stderr, "Memory Allocation Error.\n");
return NULL;
}
/* Hold the remaining part. */
strcpy(nEndStr, &ptrStr[nReplaceStartIndex+nReplaceLen]);
/* Copy characters untill the replace string. */
strncpy(nFinalStr, ptrStr, nReplaceStartIndex);
/* Copy now the insertStr. */
strncpy(&nFinalStr[nReplaceStartIndex], insertStr, nInsertLen);
/* Append the final characters. */
strcpy(&nFinalStr[nReplaceStartIndex+nInsertLen], nEndStr);
/* Free what is unused. */
free(nEndStr);
/* Return the str. */
return nFinalStr;
}
}
}
/* Main. */
int main(int argc, char *argv[])
{
char *nInitString = "This is the string.";
char *nFinalStr = ReplaceStrInsideString(nInitString, "the", "is not");
printf("Initial String :\t%s\nString Replaced:\t%s\n\n",nInitString, nFinalStr);
printf("Hit enter to continue....");
getchar();
}
Printed Results:
Initial String : This is the string.
String Replaced: This is is not string.
Hit enter to continue....
(Well memmove can be usefull here......xmmmmmmmmmmmmm)