Perl: Count number of a specific character in a string
I needed to count how many *
characters were in a string, so I wrote this simple function.
sub char_count {
my ($needle,$str) = @_;
my $len = length($str);
my $ret = 0;
for (my $i = 0; $i < $len; $i++) {
my $found = substr($str,$i,1);
if ($needle eq $found) { $ret++; }
}
return $ret;
}
You can also write it using tr
:
sub char_count {
my ($needle,$haystack) = @_;
my $count = $haystack =~ tr/$needle//;
return $count;
}
Tags:
Leave A Reply
- 2 Replies
Replies
October 2nd 2013 - john
sub char_count { scalar grep {$_ eq $_[0]} split(//, $_[1]) }
my $str = "Don't know what Larry would say, but I think this is a more perl-style version of your function.";
printf("The character 'o' is contained %d times in the stringn", char_count("o", $str));
October 18th 2013 - Steven Haryanto
Many people write:
$count = 0; $count++ while $str =~ /needle/g;
You can also write:
$count = @{[ $str =~ /needle/g ]};