in reply to The nth occurrence of a character
Does no one use index() anymore?!?
#!/usr/bin/perl use warnings; use strict; sub find_nth { my ($s,$c,$n) = @_; my $pos = -1; while ($n--) { $pos = index($s,$c,$pos+1); return -1 if $pos == -1; } return $pos; } my $str="Now is the time for all good men to come to the aid of their +country"; my $n = 5; my $c = "o"; print find_nth($str,$c,$n), "\n";
I'll leave it to those people who like to benchmark to decide whether or not this is an "efficient Perl function" :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: The nth occurrence of a character
by duff (Parson) on Feb 09, 2006 at 06:07 UTC |