Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

(dkubb) Re: (3) Answer: How do I replace a substring (if exists) with a different substring in a string?

by dkubb (Deacon)
on Jul 22, 2001 at 02:00 UTC ( #98706=note: print w/replies, xml ) Need Help??


in reply to Re: How do I replace a substring (if exists) with a different substring in a string?
in thread How do I replace a substring (if exists) with a different substring in a string?

Note: I found a bug in my earlier answer, since I can't edit it, I am posting this follow up. If the string to replace has the substring you are trying to find, it can get into an endless loop. Here is an updated ansewer:

my $string = '01234567890'; my $find = '0'; my $replace = 'a'; my $pos = index($string, $find); while($pos > -1) { substr($string, $pos, length($find), $replace); $pos = index($string, $find, $pos + length($replace)); }

In this case, an s/// regex is actually 5% faster.

  • Comment on (dkubb) Re: (3) Answer: How do I replace a substring (if exists) with a different substring in a string?
  • Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://98706]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2022-12-08 03:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?