fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. char *remove_substring(char *s, int p, int n) {
  6. // You need to do some checking before calling malloc
  7. if (n == 0) return s;
  8. size_t len = strlen(s);
  9. if (n < 0 || p < 0 || p+n > len) return NULL;
  10. size_t rlen = len-n+1;
  11. char *res = malloc(rlen);
  12. if (res == NULL) return NULL;
  13. char *pt = res;
  14. // Now let's use the two familiar loops,
  15. // except printf("%c"...) will be replaced with *p++ = ...
  16. for (int i = 0; i < p; i++) {
  17. *pt++ = s[i];
  18. }
  19. for (int i = p+n; i < strlen(s); i++) {
  20. *pt++ = s[i];
  21. }
  22. *pt = '\0';
  23. return res;
  24. }
  25.  
  26. int main(void) {
  27. char *s = remove_substring("abcdefghi",4,3);
  28. printf("%s\n", s);
  29. free(s);
  30. return 0;
  31. }
  32.  
Success #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
abcdhi