C, char, find, function, program, replace, spaces, string, trim
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
C, char, find, function, program, replace, trim
In Bookmarks on March 12, 2008 at 5:42 am
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
blank, C, copy, find, null, program, remove, replace, space, string, trim
In C, Linux on December 13, 2007 at 6:50 am
#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