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