Skip to content

Commit

Permalink
Fix str_replace
Browse files Browse the repository at this point in the history
  • Loading branch information
cnphil committed Apr 5, 2013
1 parent 9db84f1 commit 05b414b
Showing 1 changed file with 11 additions and 38 deletions.
49 changes: 11 additions & 38 deletions readline.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <string.h>

ssize_t
readline(int fd, char *vptr, size_t maxlen)
Expand All @@ -24,46 +25,18 @@ readline(int fd, char *vptr, size_t maxlen)
return(n);
}

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
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 || !(len_rep = strlen(rep)))
return NULL;
if (!(ins = strstr(orig, rep)))
return NULL;
if (!with)
with = "";
len_with = strlen(with);
char *replace_str(char *str, char *orig, char *rep)
{
static char buffer[4096];
char *p;

for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
}
if(!(p = strstr(str, orig))) // Is 'orig' even in 'str'?
return str;

// 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);
strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$
buffer[p-str] = '\0';

if (!result)
return NULL;
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));

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;
return buffer;
}

0 comments on commit 05b414b

Please sign in to comment.