agraja.wordpress.com

C Find Replace Program

In Bookmarks on March 19, 2008 at 1:35 pm

Download here. string_replace.pdf

// Filename : string_replace.c

// Author : A.G.Raja

// Website : agraja.wordpress.com

// License : GPL

#include <stdio.h>

 

 

char* string_replace(unsigned char *from, char *find, char *replace)

{

const char *p;

char *q, *to;

int i,d, match;

to=malloc(sizeof(char)*strlen(from)*strlen(replace)/strlen(find));

 

for(p = from, q = to; *p != ”; p++)

{

// find logic

for(d=0;d<strlen(find);d++)

{

if (*(p+d) == *(find+d)) match=1;

else match =0;

}

// replace logic

if (match)

{

for(i=0;i<strlen(replace);i++)

{

*(q+i)=*(replace+i);

}

q=q+i; p=p+d-1;

}

else // copy unchanged chars

{ *q=*p; q++; }

 

} *q = ”;

return to;

}

 

 

 

 

 

 

 

 

 

 

// Test code

int main()

{

unsigned char *str = “this is original text” ;

char f[]=”original”;

char r[]=”new”;

unsigned char *str2;

printf(”before:%s\n”,str);

str2=string_replace(str,f,r);

printf(”after:%s\n”,str2);

return 0;

}

 

Download here. string_replace.pdf

Tips:

See the following pages for char replace, trim spaces

char replace

trim spaces

 

  1. [...] See this page for string replace: string replace [...]

  2. [...] See this page for string replace: string replace [...]

  3. Breaks (reads out of boundary) if the input string is smaller that the search string. Also breaks under certain conditions when the replacement string is long and the input string is short (writing into unallocated memory).

    Fixed version: http://pastebin.com/f1feac3f9

  4. Here’s a better version of the program
    http://pastebin.com/f1feac3f9

    Thanks Gary Niger.

All comments are screened for appropriateness. Commenting is a privilege, not a right. Good comments will be cherished, bad comments will be deleted.