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

I felt it was better to use a counter in perl, a shell on 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; } 
+5
source share
4 answers

Counting the number of characters per line can be done with one line in Perl (compared to your 4 lines). There is no need for sub (although there is nothing wrong with encapsulating functionality in sub). From perlfaq4 "How to count the number of occurrences of a substring inside 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"; 
+9
source

If the character is persistent, best of all:

 my $count = $str =~ tr/y//; 

If the character is a variable, I would use the following:

 my $count = length( $str =~ s/[^\Q$char\E]//rg ); 

I would only use the following if I wanted compatibility with versions of Perl older than 5.14 (since it is slower and uses more memory):

 my $count = () = $str =~ /\Q$char/g; 

The memory is not used below, but may be a little slower:

 my $count = 0; ++$count while $str =~ /\Q$char/g; 
+4
source

In the beautiful * Bash / Coreutils / Grep single line:

 $ str=ru8xysyyyyyyysss6s5s $ char=y $ fold -w 1 <<< "$str" | grep -c "$char" 8 

Or maybe,

 $ grep -o "$char" <<< "$str" | wc -l 8 

The first only works if the substring is only one character long; the second only works if the substrings do not overlap.

* Not really.

+2
source

toolic gave the correct answer, but you can not hard code your values ​​to make the program reusable.

 use strict; use warnings; die "Usage: $0 <text> <characters>" if @ARGV < 1; my $search = shift; # the string you are looking for my $str; # the input string if (@ARGV && -e $ARGV[0] || !@ARGV ) { # if str is file, or there is no str local $/; # slurp input $str = <>; # use diamond operator } else { # else just use the string $str = shift; } my $count = () = $str =~ /\Q$search\E/gms; print "Found $count of '$search' in '$str'\n"; 

This will allow you to use the program to count the occurrence of a character or line inside a line, file, or standard input. For instance:

 count.pl needles haystack.txt some_process | count.pl foo count.pl x xyzzy 
+2
source

Source: https://habr.com/ru/post/1239056/


All Articles