Skip to content

Instantly share code, notes, and snippets.

@silv3rm00n
Created December 22, 2011 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silv3rm00n/1510389 to your computer and use it in GitHub Desktop.
Save silv3rm00n/1510389 to your computer and use it in GitHub Desktop.
/*
* Search and replace a string with another string , in a string
* */
char *str_replace(char *search , char *replace , char *subject)
{
char *new_subject = NULL , *p , *temp;
int size;
//subject to work upon
new_subject = strdup(subject);
//temp needs to be max as big as original subject , it will always hold a part of unconverted string
temp = malloc(strlen(subject));
while( (p = strstr( new_subject , search)) )
{
size = strlen(new_subject) + 1 + strlen(replace) - strlen(search);
new_subject = (char*) realloc(new_subject , size );
//Copy forward string to temp;
sprintf(temp , "%s" , p + strlen(search));
//write replacement to subject
strcpy(p , replace);
//write back temp string
sprintf( p+strlen(replace) , "%s" , temp);
}
return new_subject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment