Skip to content

Commit

Permalink
new utility function
Browse files Browse the repository at this point in the history
  • Loading branch information
ziirish committed Dec 31, 2015
1 parent baf85c6 commit 53c80d3
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
52 changes: 51 additions & 1 deletion src/xutils.c
Expand Up @@ -203,7 +203,7 @@ xstrsplit (const char *src, const char *token, size_t *size)
xfree (init);
return NULL;
}
ret = xcalloc (10, sizeof (char *));
ret = xcalloc (10 + 1, sizeof (char *));
while (tmp != NULL)
{
if ((int) *size > n * 10)
Expand Down Expand Up @@ -354,6 +354,56 @@ syntax_error (const char input[], int size, int ind)
fprintf (stderr, "syntax error near '%c'\n", input[xmin (ind, size)]);
}

char *
xstrreplace (const char *string, const char *substr, const char *replacement)
{
char *tok = NULL;
char *newstr = NULL;
char *oldstr = NULL;
/* if either substr or replacement is NULL, duplicate string a let caller handle it */
if ( substr == NULL || replacement == NULL )
{
return xstrdup (string);
}
newstr = xstrdup (string);
while ( (tok = strstr ( newstr, substr )) )
{
oldstr = newstr;
newstr = xmalloc (
xstrlen ( oldstr ) -
xstrlen ( substr ) +
xstrlen ( replacement ) +
1
);
/*failed to alloc mem, free old string and return NULL */
if ( newstr == NULL ){
xfree (oldstr);
return NULL;
}
memcpy ( newstr, oldstr, tok - oldstr );
memcpy (
newstr + (tok - oldstr),
replacement,
xstrlen ( replacement )
);
memcpy (
newstr + (tok - oldstr) + xstrlen( replacement ),
tok + xstrlen ( substr ),
xstrlen ( oldstr ) - xstrlen ( substr ) - ( tok - oldstr )
);
memset (
newstr +
xstrlen ( oldstr ) -
xstrlen ( substr ) +
xstrlen ( replacement ),
0,
1
);
xfree (oldstr);
}
return newstr;
}

char *
xstrsub (const char *src, int begin, int len)
{
Expand Down
11 changes: 11 additions & 0 deletions src/xutils.h
Expand Up @@ -137,6 +137,17 @@ int xstrcmp (const char *c1, const char *c2);
*/
char *xstrcat (char *dest, const char *src);

/**
* Replaces a part of a string
* @param string Original string
* @param substr Substring we want to replace
* @param replacement Replacement string
* @return new allocated string
*/
char *xstrreplace (const char *string,
const char *substr,
const char *replacement);

/**
* Splits a string into an array of strings using the given tokenizer
* @param src String to split
Expand Down

0 comments on commit 53c80d3

Please sign in to comment.