Link to home
Start Free TrialLog in
Avatar of yongsing
yongsing

asked on

Replace all occurences of a string

I would like to replace all occurences of a particular string in another string. Example:

Replace all "X" with "XX" :
"ABCXXDEFX" -> "ABCXXXXDEFXX"

Can anyone provide me with a function that do that?
Avatar of sunnycoder
sunnycoder
Flag of India image

Hi yongsing,

This is unsafe to do. Your source string may not have enough memory to hold all replacements and program may crash. Best way will be to create a dynamic temporary buffer and copy the source string part by part, replacing as necessary ... something like

while ( (temp = strstr (current, pattern)) != NULL )
{
           copy from current to temp into buffer  // you need to check for buffer full before copy
           copy string replacement to buffer // again check for sufficient memory before copy
           move current to end of replaced string
           move current to temp+strlen(pattern)
}

Cheers!
sunnycoder
Avatar of yongsing
yongsing

ASKER

>> This is unsafe to do. Your source string may not have enough
>> memory to hold all replacements and program may crash.

I know! You can assume that the memory is big enough to hold the replacements. Of course if you can provide me with code that actually re-allocates the memory as required, that would be great!
ASKER CERTIFIED SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you want to write safe programs, *NEVER EVER* assume that the memory is big enough to hold a string that may change from one run to another. Later on, you or someone else might want to modify the code to take the search string and replacement string as arguments to the program. Then, in all probability, your compiled binary *will* have a *BIG* problem.

Manav
If you are assuming default C implementation of strings, then you need to reshape your arrays etc .
I would suggest if you have any control over writing your own string structure, you can create a linked-list kind of string ,
where you will need to add Nodes in between your linked list (when new chars are added) or
to delete Nodes (when there are characters to be removed).

Easiest of all:

If there is no language constraint ,you can use PERL's "tr" function.

#!/usr/bin/perl

$mystring = "ABCXXDEFX" ;  # or take from input $_;
$mystring =~ tr/X/XX/   ;       # and you will see that $mystring now contains the desired string.


Cheers
:)-
Not tr/// in this case you would use s///g
> If you want to write safe programs, *NEVER EVER* assume that the memory is big enough to hold a string that may change from one run to another.

I think a lot of you may know this quote:
... surely where thou typest "foo" someone someday shall type "supercalifragilisticexpialidocious".