Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of occurrences of a string inside another (Perl)

What is the fastest way to count the number of times a certain string appears in a bigger one? My best guess would be to replace all instances of that string with nothing, calculate the difference of lengths and divide by the length of the substring, but that seems rather slow, and I need to analyze big amounts of data.

like image 949
ronash Avatar asked Mar 02 '12 18:03

ronash


People also ask

How do you count occurrences of a character inside a string?

Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.

How do I count the number of characters in a string in Perl?

The length function works only on strings, not on arrays. An array stores an ordered list and is preceded by an @ sign and populated using parentheses. To find out the length of an array, use the scalar function.

How do I use substring in Perl?

substr() in Perl returns a substring out of the string passed to the function starting from a given index up to the length specified. This function by default returns the remaining part of the string starting from the given index if the length is not specified.


1 Answers

You can capture the strings, then count them. It can be done by applying a list context to the capture with ():

my $x = "foo"; my $y = "foo foo foo bar"; my $c = () = $y =~ /$x/g;  # $c is now 3 

You can also capture to an array and count the array. Same principle, different technique:

my @c = $y =~ /$x/g; my $count = @c; 
like image 136
TLP Avatar answered Sep 25 '22 12:09

TLP