This was very interesting indeed as it was more difficult to implement.
But after a few try, i have succeeded.
I didn't use the "case" condotional structure.
Here is the result:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *ReplaceString( char *buff, char *oldstring, char *newstring )
{
char *bkp = (char*)malloc( sizeof(char) * strlen( buff ) * (strlen(oldstring) + 1));
char *tmp = (char*)malloc( sizeof(char) * strlen( buff ) * (strlen(newstring) + 1));
if( !bkp || !tmp )
{
fputs( "memory allocation has fail.\n", stderr );
return (NULL);
}
const int max_size = 10000;
if( strlen( tmp ) > max_size )
{
fputs("not enough space in the buffer \"newbuff\"\n", stderr);
return (NULL);
}
char newbuff[max_size];
unsigned int len = strlen(oldstring);
int pos;
char *pdest;
int i = 0;
strcpy( bkp, buff );
tmp[0] = 0;
newbuff[0] = 0;
while( buff != 0 )
{
pdest = strstr( buff, oldstring );
pos = pdest - buff + 1;
while( pdest != NULL )
{
bkp[pos - 1] = 0;
strcat( bkp, newstring );
strcat( tmp, bkp );
buff += pos + len - 1;
strcpy( bkp, buff );
pdest = strstr( buff, oldstring );
pos = pdest - buff + 1;
}
i++;
}
strcat( tmp, buff );
strcat( newbuff, tmp );
free( bkp );
free( tmp );
return newbuff;
}
void main()
{
char *String = "hi how aaa-AAAre you doing todaaa-AAAy ?";
char *oldstring = "aaa-AAA";
char *newstring = "a";
char *temp;
temp = ReplaceString( String, oldstring, newstring );
if( temp != NULL )
{
printf("String = %s\n", String);
printf("String = %s\n", temp );
}
}