#include #include #include #include #include //https://stackoverflow.com/a/779960/8229149 char *str_replace(char *orig, char *rep, char *with) { char *result; // the return string char *ins; // the next insert point char *tmp; // varies int len_rep; // length of rep (the string to remove) int len_with; // length of with (the string to replace rep with) int len_front; // distance between rep and end of last rep int count; // number of replacements // sanity checks and initialization if (!orig || !rep) return NULL; len_rep = strlen(rep); if (len_rep == 0) return NULL; // empty rep causes infinite loop during count if (!with) with = ""; len_with = strlen(with); // count the number of replacements needed ins = orig; for (count = 0; (tmp = strstr(ins, rep)); ++count) { ins = tmp + len_rep; } tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1); if (!result) return NULL; // first time through the loop, all the variable are set correctly // from here on, // tmp points to the end of the result string // ins points to the next occurrence of rep in orig // orig points to the remainder of orig after "end of rep" while (count--) { ins = strstr(orig, rep); len_front = ins - orig; tmp = strncpy(tmp, orig, len_front) + len_front; tmp = strcpy(tmp, with) + len_with; orig += len_front + len_rep; // move to next "end of rep" } strcpy(tmp, orig); return result; } /* char *str_index_replace(char *orig, int rep_s, int rep_e, char *with) { // Ugh, Re-worked the preceding str_replace function to work with indexes char *result; // the return string char *ins; // the next insert point char *tmp; // varies int len_rep; // length of rep (the string to remove) int len_with; // length of with (the string to replace rep with) int len_front; // distance between rep and end of last rep // sanity checks and initialization if (!orig || !rep_e){ DEBUG_ERROR("[orig or rep_e is false] *orig=%p; rep_s=%d, rep_e=%d\n", 67, orig, rep_s, rep_e); return NULL; } len_rep = rep_e - rep_s; if (len_rep == 0){ DEBUG_ERROR("[rep empty]\n", 72); return NULL; // empty rep causes infinite loop during count } if (!with) with = ""; len_with = strlen(with); tmp = result = malloc(strlen(orig) + (len_with - len_rep) + 1); if (!result) { DEBUG_ERROR("[bad malloc]", 83); return NULL; } // first time through the loop, all the variable are set correctly // from here on, // tmp points to the end of the result string // ins points to the next occurrence of rep in orig // orig points to the remainder of orig after "end of rep" ins = orig + rep_s; len_front = ins - orig; tmp = strncpy(tmp, orig, len_front) + len_front; tmp = strcpy(tmp, with) + len_with; orig += len_front + len_rep; // move to next "end of rep" strcpy(tmp, orig); return result; } */