Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Replacing a given character starting with the xth occurence in a string

by Dr. Mu (Hermit)
on May 22, 2001 at 10:53 UTC ( [id://82175]=note: print w/replies, xml ) Need Help??


in reply to Replacing a given character starting with the xth occurence in a string

The following works without using any explicit iterations. I haven't clocked its execution against the others, though.
$s = 'abc nbc cbs fox hbo sho cnn rox'; ($orig, $num, $subst) = ('n', 2, '-'); $s =~ s/^(([^$orig]*$orig){$num})(.*)/$1/; ($t = $3) =~ s/$orig/$subst/g; $s .= $t; print $s
This prints:
abc nbc cbs fox hbo sho cn- rox
It works by cutting the string into two parts, applying the substitution to the second part (if there is one) and rejoining them.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2024-04-23 07:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found