Substituicao De Substring Numa String

Este código substitui uma substring por outra numa string em linguagem C.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *troca(char * , char *, char *);

int main( void ){

char A[100], B[100], C[100];

printf("DIGITE UMA STRING:\n");
scanf("%[A-Z a-z]s", &A);

printf("DIGITE A STRING QUE SERÁ SUBSTITUIDA:\n");
scanf("%[A-Z a-z]s", &B);

printf("DIGITE A NOVA STRING:\n");
scanf("%[A-Z a-z]s", &C);

printf("RESULTADO: ", troca(A,B,C));

system ("PAUSE");
return 0 ;
}

char *troca (char *A , char *B, char *C) {

int i=0, l=0, k, j;
char *extra, *aux;

aux = (char * ) malloc(303 * sizeof (char));

while (A[i] != '\0'){

j=0;
while(A[i+j] == B[j] && A[i+j] != '\0' && B[j] != '\0'){

if (B[j+1] == '\0'){

for (k=0; k<strlen(C); k++)
aux[i+k] = C[k];

l = l + strlen(C);
i = i + strlen(B);
j=0;
} //fim do bloco if
else
j++;

} //fim do bloco while mais interno

aux[l] = A[i];
i++;
l++;
} //fim do bloco while mais externo

aux[i] = A[l];

extra = (char *) malloc ((strlen(aux)+1) * sizeof (char));
strcpy(extra,aux);
free(aux);

return extra;

} //fim da função troca

Salvo indicação em contrário, o conteúdo desta página é licenciado sob Creative Commons Attribution-ShareAlike 3.0 License