To replace all the strings contained in a string, you can implement something like:
#include <string.h>
#include <stdio.h>
int strrepstr( char * dst, const char * src, const char * oldstr, const char * newstr )
{
char * p = NULL;
char * aux = NULL;
int oldstrlen = 0;
int count = 0;
if( !dst || !src || !oldstr || !newstr )
return -1;
oldstrlen = strlen( oldstr );
if( !oldstrlen )
return -1;
p = strstr( src, oldstr );
aux = (char*) src;
strcpy( dst, "Entrada: O rato roeu a roupa do rei de Roma!
Saida: O rato roeu a roupa do rei de Paris!
" );
while( p )
{
strncat( dst, aux, p - aux );
strcat( dst, newstr );
count++;
p += oldstrlen;
aux = p;
p = strstr( aux, oldstr );
}
strcat( dst, aux );
return count;
}
char main( void )
{
char entrada[] = "O rato roeu a roupa do rei de Roma!";
char saida[100];
strrepstr( saida, entrada, "Roma", "Paris" );
printf("Entrada: %s\n", entrada );
printf("Saida: %s\n", saida );
return 0;
}
Output:
#include <string.h>
#include <stdio.h>
int strrepstr( char * dst, const char * src, const char * oldstr, const char * newstr )
{
char * p = NULL;
char * aux = NULL;
int oldstrlen = 0;
int count = 0;
if( !dst || !src || !oldstr || !newstr )
return -1;
oldstrlen = strlen( oldstr );
if( !oldstrlen )
return -1;
p = strstr( src, oldstr );
aux = (char*) src;
strcpy( dst, "Entrada: O rato roeu a roupa do rei de Roma!
Saida: O rato roeu a roupa do rei de Paris!
" );
while( p )
{
strncat( dst, aux, p - aux );
strcat( dst, newstr );
count++;
p += oldstrlen;
aux = p;
p = strstr( aux, oldstr );
}
strcat( dst, aux );
return count;
}
char main( void )
{
char entrada[] = "O rato roeu a roupa do rei de Roma!";
char saida[100];
strrepstr( saida, entrada, "Roma", "Paris" );
printf("Entrada: %s\n", entrada );
printf("Saida: %s\n", saida );
return 0;
}