Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: (bbfu) (another way) Re: Replacing a given character starting with the xth occurence in a string

by MeowChow (Vicar)
on May 21, 2001 at 09:36 UTC ( [id://81917]=note: print w/replies, xml ) Need Help??


in reply to (bbfu) (another way) Re: Replacing a given character starting with the xth occurence in a string
in thread Replacing a given character starting with the xth occurence in a string

Your solution has a few subtle bugs, try it with:
print mine ("Terence and Philip are sweet", 'c', 'Z', 3);
This happens because $pos is set to -1 after not finding a second 'c', and since you are indexing from $pos + 1, which has become 0, index searches from the start of the string, again.

You should also initialize $pos to -1, not zero, for similar reasons (otherwise it ignores the first character in the string).

Getting this problem right, without boundary or fencepost erros, employing manual indexing and positioning is remarkably tricky. So much so, that I'm not even sure the following fixed-up code is error-free:

sub crep { my ($str, $chr, $rep, $nth) = @_; my $pos = 0; while (--$nth > 0) { $pos = index $str, $chr, $pos; last if $pos < 0; $pos++; } substr ($str, $pos) =~ s/$chr/$rep/g if $pos >= 0; return $str; }
I would really like to see if this can be improved upon, assuming the same method is used. In the meantime, here's a slight variant, which I believe to be correct:
sub crep { my ($str, $chr, $rep, $num) = @_; my $tstr = ''; $tstr .= substr $str, 0, (1 + index $str, $chr), '' while --$num; $str =~ s/$chr/$rep/g; $tstr.$str; }
update: I'm beginning to believe that this problem is the poster-child for unit testing! A more promising possibility... caveat emptor as always:
sub crep { my ($str, $chr, $rep, $num) = @_; $str !~ /$chr/g and return $str while $num--; substr ($str, -1 + pos $str) =~ s/$chr/$rep/g; return $str; }
Of course, this one dances around the index problem with a regex.

update2: Improving on the original fix...

sub crep { my ($str, $chr, $rep, $nth) = @_; my $pos = 0; ($pos = index $str, $chr, $pos)++ < 0 and return $str while --$nth; substr ($str, $pos) =~ s/$chr/$rep/g; return $str; }
   MeowChow                                   
               s aamecha.s a..a\u$&owag.print
  • Comment on Re: (bbfu) (another way) Re: Replacing a given character starting with the xth occurence 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://81917]
help
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found