Good night!
I resolve the problem of segmentation fault and I run my code and I can use my program to change a substring to other substring in a string. But i can't use my program to change substrings with different lengths. I gonna show you.
Code:
#include <stdio.h>
int my_strlen(char *s)
{
char *p = s;
while (*p != '\0')
p++;
return p - s;
}
char * my_strstr(const char *string, const char *substring)
{
for (;;) {
const char* p = substring;
const char* q = string++;
while (*p && *p == *q)
p++, q++;
if (*p == 0)
return (char*)string - 1;
if (*q == 0)
return (NULL);
}
}
char * strsubst(char * s, const char * old_s, const char * new_s)
{
char *aux=NULL;
int tamanho1,i;
tamanho1=my_strlen((char*)old_s);
aux = my_strstr(s,old_s);
if(aux)
{
for(i = 0; i< tamanho1; i++)
s[(aux - s) + i] = new_s[i];
return(s);
}
else
return NULL;
}
int main()
{
char string[40],antiga[10],nova[10];
printf("\n");
printf("Entre com a string :");
gets(string);
printf("\n");
printf("Entre com a antiga palavra :");
gets(antiga);
printf("\n");
printf("Entre com a nova palavra :");
gets(nova);
printf("\n");
printf("nova string ==> %s\n",strsubst(string,antiga,nova));
return(0);
}
Example with same lengths:
Entre com a string :My club is the best
Entre com a antiga palavra :best
Entre com a nova palavra oor
nova string ==> My club is the poor
Example with the old_s bigger than new_s
Entre com a string :My club is the best
Entre com a antiga palavra :is
Entre com a nova palavra :a
nova string ==> My club a
Example with the new_s bigger than old_s
Entre com a string :My club is the best
Entre com a antiga palavra :My
Entre com a nova palavra :Our
nova string ==> Ou club is the best
This is the problems. I don't know where is the problem if you can help I thanks to you. What alterations I have to do in my code?