1. Java 언어의 String.replace() 메쏘드와 유사한 기능의 C 함수입니다
2. Visual C/C++ 6.0 및 gcc에서 잘 동작하도록 작성되었습니다.
3. 메모리 누수(memory leak) 현상을 최대한 줄이려고 노력하였답니다.
출처: http://blog.empas.com/javaclue/22720841
#include <stdio.h>
#include <string.h>
#define FREE(x) if(x != NULL){free(x); x = NULL;}
/* --------------------------------------------------------
replaceAll(char *srcStr, char *patStr, char *repStr)
Convert a string to another string in which
every substring, matched with the given pattern,
is replaced to the given replacement substring.
The source string is not changed.
Parameters
srcstr: the source string
patstr: the pattern substring to be matched
repstr: replacement substring
Returns
the new string.
-------------------------------------------------------- */
char *replaceAll(char *srcstr, char *patstr, char *repstr)
{
char *str = srcstr;
char *idx;
char *newstr = NULL; // new string with replaced stuff
char *tmpstr; // temporary pointer to a string
char *pstr = newstr;
int replen = strlen(repstr);
int patlen = strlen(patstr);
int newlen = 0;
int counter = 0;
int sizealloc = 0;
if (patlen < 1)
{
sizealloc = strlen(srcstr) + counter*(replen - patlen) + 1;
tmpstr = (char *) realloc(newstr, sizealloc);
if (tmpstr == NULL)
{
fprintf(stderr, "ERROR: realloc failed");
if (newstr)
free(newstr);
newstr = NULL;
return NULL;
}
newstr = tmpstr;
newstr = strcpy(newstr, srcstr);
return newstr;
}
while (idx = strstr(str, patstr))
{
counter++;
str = idx + patlen;
}
if (counter > 0)
{
str = srcstr;
sizealloc = strlen(srcstr) + counter*(replen - patlen) + 1;
tmpstr = (char *) realloc(newstr, sizealloc);
if (tmpstr == NULL)
{
fprintf(stderr, "ERROR: realloc failed");
if (newstr)
free(newstr);
newstr = NULL;
return NULL;
}
newstr = tmpstr;
pstr = newstr;
while (idx = strstr(str, patstr))
{
if (idx - str > 0)
{
newstr = strncat(newstr, str, idx - str);
}
newstr = strcat(newstr, repstr);
str = idx + patlen;
}
}
else
{
sizealloc = strlen(srcstr) + counter*(replen - patlen) + 1;
tmpstr = (char *) realloc(newstr, sizealloc);
if (tmpstr == NULL)
{
fprintf(stderr, "ERROR: realloc failed");
if (newstr)
free(newstr);
newstr = NULL;
return NULL;
}
newstr = tmpstr;
newstr = strcpy(newstr, srcstr);
}
return newstr;
}