fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. char* replaceSubstring(const char* str, const char* oldSub, const char* newSub) {
  6. const char* pos = strstr(str, oldSub);
  7. if (!pos) return strdup(str); // oldSub not found, return original string
  8.  
  9. size_t beforeLen = pos - str;
  10. size_t oldLen = strlen(oldSub);
  11. size_t newLen = strlen(newSub);
  12. size_t afterLen = strlen(pos + oldLen);
  13.  
  14. // Allocate memory for new string
  15. char* result = malloc(beforeLen + newLen + afterLen + 1);
  16. if (!result) return NULL;
  17.  
  18. // Copy parts
  19. memcpy(result, str, beforeLen);
  20. memcpy(result + beforeLen, newSub, newLen);
  21. memcpy(result + beforeLen + newLen, pos + oldLen, afterLen);
  22. result[beforeLen + newLen + afterLen] = '\0';
  23.  
  24. return result;
  25. }
  26.  
  27. int main() {
  28. const char* original = "Hello World!";
  29. const char* oldSub = "World";
  30. const char* newSub = "C";
  31.  
  32. char* replaced = replaceSubstring(original, oldSub, newSub);
  33. printf("Result: %s\n", replaced);
  34.  
  35. free(replaced);
  36. return 0;
  37. }
  38.  
  39.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
Result: Hello C!