473,385 Members | 1,772 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Replacing one string with another

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;
}
-------------------------------------------------
Jul 14 '08 #1
2 2468
ke************@googlemail.com wrote:
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]
Jul 14 '08 #2
ke************@googlemail.com wrote:
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 ) );
It seems unlikely that this is what you meant. If the
numerator is not too large for a size_t, the argument is
just strlen(replace), a value that doesn't seem useful for
anything much. If the numerator *is* too big, the computed
value will be even less useful ...

Oh, and you forgot to check whether malloc() succeeded.
for( p = find, q = to; *p; p++ )
{
for( d = 0; d < strlen( find ); d++ )
{
if( *(p + d) == *(find + d) )
match = 1;
else
match = 0;
}
I don't see how this can be right, either. After `p' has
incremented one or more times from its initial value, `d' is
still happy to go all the way up to strlen(find) -- and that
means that `*(p+d)' can attempt to access bytes beyond the end
of the string ...
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;
}
Since this has a homework-y flavor about it I won't offer
complete code. But here's an outline of how the code might be
written:

1) Scan through the original string once, just to count the
number of times the "find" string appears. The strstr()
function will be useful here; remember that after finding
an occurrence of "find" you should skip past the whole
thing before searching again. (Otherwise, a "find" string
like "##" would give an incorrect count on an input like
"My telephone number is ###-###-####.")

2) Knowing the length of the original string, the length of
the "find" string, the length of the replacement, and the
number of matches, you can now calculate how much space the
result string will need. Allocate that much space (don't
forget room for the terminating '\0'). If malloc() returns
NULL, just return NULL without proceeding further.

3) Now make a second pass through the string, looking for
occurrences of the "find" string. Copy everything before
the match to the result (starting from the beginning of
the original or from the end of the previous "find"), then
add a copy of the replacement string. The memcpy() function
will be useful here, because you're dealing with pieces of
strings that are not themselves strings.

4) Finally, copy the unmatched tail end of the original string
to the result, not forgetting to include the '\0'. The
strcpy() function will be useful here.

--
Er*********@sun.com

Jul 14 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: C# Learner | last post by:
What's the "standard" way of replacing a character in a string? Obviously, I can't say "myString = character;" because strings are immutable... So what would be the "standard" way of doing this?...
11
by: Dimitris Georgakopuolos | last post by:
Hello, I have a text file that I load up to a string. The text includes certain expression like {firstName} or {userName} that I want to match and then replace with a new expression. However,...
7
by: VMI | last post by:
If I have the string "Héllo", how can I replace char (é) with an 'e'? I cannot use the String.Replace() fuction. It has to be by replacing one char with another. Thanks.
11
by: lucky | last post by:
hi, i got file which contains "----------------" in a line. the line only contains this data as a saperation. using regular expression i want to i detify the line contains that data and replace...
12
by: anonymous | last post by:
Hello, I need to replace this char  with another char. However I am not able to acieve this. I tried this but it doesnt work: str = str.Replace(chr(asc(194)), "") Can somebody help ?
7
by: Ryan Taylor | last post by:
Hi. I have some code that dynamically generates a PDF and spits this content directly to the web browser. I use HTMLDoc to create the Pdf's from html. So the user can click on a button "Print...
1
by: WT | last post by:
Hello, I was using hastable to store collection of objects of the same class MyClass. I start replacing this hastable by a Dictionary<string,MyClass>....but I was storing this hastable in cache...
3
by: skinnybloke | last post by:
Hi - I have the following VB function within MS Access which is called via a query. How do I modify this code so that it will only do the replacement based upon the value of another field on the...
7
by: DarthBob88 | last post by:
I have to go through a file and replace any occurrences of a given string with the desired string, like replacing "bug" with "feature". This is made more complicated by the fact that I have to do...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.