Replacing one string with another


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;
}
-------------------------------------------------
 
Ad

Advertisements

3

31349 83652

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 )

___________________________________ ^^^^^
orig is never used anywhere

[snip]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top