X-Git-Url: https://git.wpitchoune.net/gitweb/?p=prss.git;a=blobdiff_plain;f=src%2Fpstr.c;fp=src%2Fpstr.c;h=fb4f937da116cf22cb7897a067aae92c25b340f5;hp=0000000000000000000000000000000000000000;hb=24fbad1fafb0e7c0cd65afb199a29a8676db5b5e;hpb=b182d98e4534d7b84a4d99c08b0f343e80d64ee4 diff --git a/src/pstr.c b/src/pstr.c new file mode 100644 index 0000000..fb4f937 --- /dev/null +++ b/src/pstr.c @@ -0,0 +1,100 @@ +/* + Copyright (C) 2011-2014 jeanfi@gmail.com + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA + */ + +#include + +#include + +char *strrep(char *str, const char *old, const char *new) +{ + char *p, *res; + int pos; + + if (!str) + return NULL; + + if (!*str || !old || !*old || !new || !strcmp(old, new)) + return str; + + p = strstr(str, old); + + if (!p) + return str; + + res = malloc(strlen(str) + (new ? strlen(new) : 0) - strlen(old) + 1); + + pos = p - str; + + strncpy(res, str, pos); + res[pos] = '\0'; + + if (new) + strcat(res + pos, new); + + strcat(res, str + pos + strlen(old)); + + return res; +} + +/* + Derivated from http://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c +*/ +char *strrepg(char *orig, const char *rep, const char *with) { + char *result; // the return string + char *ins; // the next insert point + char *tmp; // varies + int len_rep; // length of rep + int len_with; // length of with + int len_front; // distance between rep and end of last rep + int count; // number of replacements + + if (!orig) + return NULL; + if (!rep) + rep = ""; + len_rep = strlen(rep); + if (!with) + with = ""; + len_with = strlen(with); + + ins = orig; + for(count = 0; (tmp = strstr(ins, rep)); count++) { + ins = tmp + len_rep; + } + + // 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" + tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1); + + if (!result) + return NULL; + + 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; +}