C Find Replace Program

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

 

Advertisements

C Find and Replace program

Download here. find_replace.pdf

// Filename : find_replace.c

// Author : A.G.Raja

// Website : agraja.wordpress.com

// License : GPL

#include <stdio.h>

void find_replace(char *to, unsigned char *from, char find, char replace)

{

const char *p; char *q;

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

{

if ( *p != find)

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

else

{ *q=replace; q++; }

} *q = ”;

}

int main()

{

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

unsigned char str2[strlen(str)];

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

find_replace(str2,str,’s’,’x’);

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

return 0;

}

 

 

// This program can be used for single char only.

// string with more than one char is not supported

Download here. find_replace.pdf

Tips:

This function can be used to trim white spaces in file.

See this page for an example: Trim

See this page for string replace: string replace

 

 

 

 

C program to trim blank spaces

#include <stdio.h>

void copy(char *to, char *from);

int main(void)
{

char str[80];

copy (str,” this ia a test “);

printf(“without spaces:%s”,str);

return 0;

}

void copy(char *to, char *from)

{

const char *p; char *q;

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

// space between quotes in the above statement
{

if (*p != ‘ ‘) { *q=*p; q++; }

}

*q = ”;

}

// Download here.

// trim.doc

Tips: This function can be modified to find and replace a char.

See this page for an example Find and Replace

See this page for string replace: string replace