C search and replace string program
Linux
IT
The other day I needed to write a C function which search and replace all tokens in a char * aka C strings. Searching on google doesn't returned too many promising results, hence I ended up writing my own function. Here it goes:
/*
* casr --- C based search and replace program in a char *
*
* Author: Usman Saleem - usman.saleem@gmail.com
*
* This code is released under The MIT License.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyrights (c) 2010, Usman Saleem.
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* The search and replace function attempts to replace
* 'token' with 'replacement' on a copy of 'line'.
* Returns:
* - NULL for invalid arguments or out of memory
* - 'line' reference if nothing to replace
* - char * with all tokens replaced.
*
* The caller should call free if the reference to 'line' and
* returned value is different
*/
char * csar(char *line, char *token, char *replacement)
{
char *result, *finalresult; /* the return string */
int token_length; /* length of token */
int replacement_length; /* length of replacement */
int count; /* number of replacements */
char *tmp;
char *curr;
int diff;
/* Basic sanity of arguments */
if (!line)
return NULL;
if (!token || !(token_length = strlen (token)))
return NULL;
if (!replacement || !(replacement_length = strlen (replacement)))
return NULL;
/*return same line if there is nothing to replace */
if (!(strstr (line, token)))
return line;
curr = line;
/*determine count of tokens */
for(count = 0; tmp = strstr(curr,token); count++)
{
curr = tmp+token_length;
}
/*allocate memory*/
finalresult = result = malloc(strlen(line) + (replacement_length*count) + 1 - (token_length*count));
if(!result)
{
return NULL; /*out of memory?*/
}
/*move to beginning of line*/
curr = line;
for(;;)
{
/*determine next location of token */
tmp = strstr(curr, token);
if(!tmp) break;
diff = tmp - curr;
strncpy(result, curr, diff); /*copy the pre-token part*/
strcpy(result+diff, replacement); /*copy replacement*/
strcpy(result+diff+replacement_length, tmp+token_length); /*copy rest of stuff*/
/*move to next token position*/
curr = curr+diff+token_length;
/*update result position to next replace position*/
result = result+diff+replacement_length;
}
return finalresult;
}
int main(void)
{
char *line1="";
char *line2="abcdef";
char *line3="abc@abc.txt@@def@";
char *line4="@middle@";
char *line5="@";
char *line6="@@@";
printf("line1: %s replaced with %s\n",line1, csar(line1, "@", "xxATxx"));
printf("line2: %s replaced with %s\n",line2, csar(line2, "@", "xxATxx"));
printf("line4: %s replaced with %s\n",line4, csar(line4, "@", "xxATxx"));
printf("line5: %s replaced with %s\n",line5, csar(line5, "@", "xxATxx"));
printf("line6: %s replaced with %s\n",line6, csar(line6, "@", "xxATxx"));
char *temp = csar(line3, "@", "xxATxx");
char *temp1 = csar(temp, ".", "xxDOTxx");
printf("line3: %s replaced with %s\n",line3,temp1 );
}