K
kevin.eugene08
hi all,
i'm trying to replace a string with known "tokens" with values -- and
am not sure how to do this effectively. Since i don't know the size
of the string containing the tokens to be replaced, i can't make a
buffer -- hence i thought of using malloc() -- is what i have below
effective? it doesn't seem to work though - the returned string just
returns the substituted part.
Any thoughts / comments are welcomed.
--------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *replaceString(unsigned char *orig, char *find, char *replace )
{
const char *p;
char *q, *to;
int i,d,match;
to = malloc( sizeof( char ) * strlen( find ) *
strlen( replace ) /
strlen( find ) );
for( p = find, q = to; *p; p++ )
{
for( d = 0; d < strlen( find ); d++ )
{
if( *(p + d) == *(find + d) )
match = 1;
else
match = 0;
}
if( match )
{
for( i = 0; i < strlen( replace ); i++ )
{
*(q + i ) = *(replace + i);
}
q=q+i; p=p+d-1;
}
*q=*p;q++;
*q = '\0';
}
return to;
}
int main( int argc, char **argv )
{
unsigned char *str = "This is my string %n";
char f[] = "%n";
char r[] = "23";
unsigned char *replaced;
replaced = replaceString( str, f, r );
printf( "I see: %s\n", replaced );
return 0;
}
-------------------------------------------------
i'm trying to replace a string with known "tokens" with values -- and
am not sure how to do this effectively. Since i don't know the size
of the string containing the tokens to be replaced, i can't make a
buffer -- hence i thought of using malloc() -- is what i have below
effective? it doesn't seem to work though - the returned string just
returns the substituted part.
Any thoughts / comments are welcomed.
--------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *replaceString(unsigned char *orig, char *find, char *replace )
{
const char *p;
char *q, *to;
int i,d,match;
to = malloc( sizeof( char ) * strlen( find ) *
strlen( replace ) /
strlen( find ) );
for( p = find, q = to; *p; p++ )
{
for( d = 0; d < strlen( find ); d++ )
{
if( *(p + d) == *(find + d) )
match = 1;
else
match = 0;
}
if( match )
{
for( i = 0; i < strlen( replace ); i++ )
{
*(q + i ) = *(replace + i);
}
q=q+i; p=p+d-1;
}
*q=*p;q++;
*q = '\0';
}
return to;
}
int main( int argc, char **argv )
{
unsigned char *str = "This is my string %n";
char f[] = "%n";
char r[] = "23";
unsigned char *replaced;
replaced = replaceString( str, f, r );
printf( "I see: %s\n", replaced );
return 0;
}
-------------------------------------------------