1
The intention is to replace all words toda
for 0
, however after X characters it starts returning strange values as can be observed in the comments.
I think I’m handling the parameters wrong, but at what point? Why?
#include<stdio.h>
#include<string.h>
/*
* @brief
* PHP's str_replace ported to C
* @author Silver Moon ([email protected])
*
*/
char *str_replace(char *search , char *replace , char *subject)
{
char *p = NULL , *old = NULL , *new_subject = NULL ;
int c = 0 , search_size;
search_size = strlen(search);
//Count how many occurences
for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search))
{
c++;
}
//Final size
c = ( strlen(replace) - search_size )*c + strlen(subject);
//New subject with new size
new_subject = malloc( c );
//Set it to blank
strcpy(new_subject , "");
//The start position
old = subject;
for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search))
{
//move ahead and copy some text from original subject , from a certain position
strncpy(new_subject + strlen(new_subject) , old , p - old);
//move ahead and copy the replacement text
strcpy(new_subject + strlen(new_subject) , replace);
//The new start position after this search match
old = p + search_size;
}
//Copy the part after the last search match
strcpy(new_subject + strlen(new_subject) , old);
return new_subject;
}
char* change(char *original) {
char end[100];
strcpy(end, str_replace("toda", "0", original));
return end;
}
int main()
{
char *original[100],
*final[100];
printf("digite:");
fgets(original, sizeof(original), stdin); // obtem valor -> toda toda toda toda toda toda toda toda
strcpy(final, change(original)); // salva em final o valor alterado
printf("[%s]", final); // retorna: [0 \336\3770 0 0 0 0 \220\360\277_\377]
return 0;
}
Why do you want to have 100 different strings? And why aren’t they being allocated?
– Maniero
@bigown am student, do not know much what I did, put [100] for my debugger stop giving Warning when he tries to run the fgets and strcpy
– Elaine
That’s not how it works, every time you find a problem you have to understand what it is and how to solve it. Starting to look for random solutions only increases the problem. What should appear? Eight 0s? You really need this function
change()
? It seems to me that she is cheerful there. I am even making an answer and I took it. My internet is falling all the time, and I will have to interact less and complement when possible.– Maniero
@bigown at the end of the code realized I got it wrong, all wrong :/. The intention is to appear 8x
0
yes. You can explain my mistakes?– Elaine