fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5.  
  6. char *strreplace(char * string, char * sub, char * replace);
  7.  
  8. int main(void){
  9. char * mystring = "Here is my string.";
  10. char * sub = " ";
  11. char * replace = "__++";
  12.  
  13. char * newString = strreplace(mystring, sub, replace);
  14. printf("new string: %s\n", newString);
  15. return 0;
  16. }
  17.  
  18. //my replace
  19. char *strreplace(char *string, char *sub, char *replace)
  20. {
  21. if(!string || !sub || !replace) return NULL; // we need all inputs
  22.  
  23. char *result = (char*)malloc(1); // malloc memory for new string, will be realloc later
  24. if(result == NULL){
  25. printf("malloc returned null\n");
  26. return NULL;
  27. }
  28.  
  29. char *pos = string; // set pointer of pos to start of string
  30. char *pos1; // pointer to search for sub
  31. while((pos1 = strstr(pos, sub))) // search for sub and point to start of memory location
  32. {
  33. int len = (pos1 - pos); // length = found memory locatino - beginning of string
  34. result = realloc(result, len + strlen(replace) + 1); // realloc result for string + replacemenet string + \0
  35.  
  36. strncat(result, pos, len); // pull up to this location
  37. strcat(result, replace); //replace the found (strcat is fine because we already allocated the memory)
  38. pos = (pos1 + strlen(sub)); // update pos to find next occurance of sub in string
  39. }
  40.  
  41. // if we aren't at the end of the original string, we need to get what's left of original string
  42. if(pos != (string + strlen(string)))
  43. {
  44. result = realloc(result, strlen(result) + strlen(pos) + 1); // realloc for what is left of original string
  45. strcat(result, pos); // get the rest of the original string
  46. }
  47.  
  48.  
  49. return result; // return new string
  50. }
Runtime error #stdin #stdout 0s 3100KB
stdin
Standard input is empty
stdout
Standard output is empty