Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to count occurrence of char in a string?

Tags:

sh

perl

I felt there must a better way to count occurrence instead of writing a sub in perl, shell in Linux.

#/usr/bin/perl -w
use strict;
return 1 unless $0 eq __FILE__;
main() if $0 eq __FILE__;
sub main{
    my $str = "ru8xysyyyyyyysss6s5s";
    my $char = "y";
    my $count = count_occurrence($str, $char);
    print "count<$count> of <$char> in <$str>\n";
}
sub count_occurrence{
    my ($str, $char) = @_;
    my $len = length($str);
    $str =~ s/$char//g;
    my $len_new = length($str);
    my $count = $len - $len_new;
    return $count;
}
like image 822
Gang Avatar asked Dec 23 '15 13:12

Gang


People also ask

How do you count specific occurrences of characters in a string?

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

How do you count how many times a character is repeated in a string?

Using Counter Array In the following Java program, we have used the counter array to count the occurrence of each character in a string. We have defined a for loop that iterates over the given string and increments the count variable by 1 at index based on character.

How do you count the number of occurrences of an element in a string?

Approach: First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.


1 Answers

Counting the occurences of a character in a string can be performed with one line in Perl (as compared to your 4 lines). There is no need for a sub (although there is nothing wrong with encapsulating functionality in a sub). From perlfaq4 "How can I count the number of occurrences of a substring within a string?"

use warnings;
use strict;

my $str = "ru8xysyyyyyyysss6s5s";
my $char = "y";
my $count = () = $str =~ /\Q$char/g;
print "count<$count> of <$char> in <$str>\n";
like image 184
toolic Avatar answered Sep 21 '22 17:09

toolic