fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4.  
  5. char *str_replace(char *search , char *replace , char *subject) {
  6. char *p = NULL , *old = NULL , *new_subject = NULL ;
  7. int c = 0 , search_size;
  8. search_size = strlen(search);
  9. //Count how many occurences
  10. for (p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search)) {
  11. c++;
  12. }
  13. //Final size
  14. c = ( strlen(replace) - search_size )*c + strlen(subject);
  15. //New subject with new size
  16. new_subject = malloc( c );
  17. //Set it to blank
  18. strcpy(new_subject , "");
  19. //The start position
  20. old = subject;
  21. for (p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search)) {
  22. //move ahead and copy some text from original subject , from a certain position
  23. strncpy(new_subject + strlen(new_subject) , old , p - old);
  24. //move ahead and copy the replacement text
  25. strcpy(new_subject + strlen(new_subject) , replace);
  26. //The new start position after this search match
  27. old = p + search_size;
  28. }
  29. //Copy the part after the last search match
  30. strcpy(new_subject + strlen(new_subject) , old);
  31. return new_subject;
  32. }
  33.  
  34. int main() {
  35. char original[100], final[100];
  36. printf("digite:");
  37. fgets(original, sizeof(original), stdin);
  38. strcpy(final, str_replace("toda", "0", original));
  39. printf("[%s]", final);
  40. }
  41.  
  42. //https://pt.stackoverflow.com/q/209982/101
Success #stdin #stdout 0s 10304KB
stdin
toda toda toda toda toda toda toda toda
stdout
digite:[0 0 0 0 0 0 0 0
]