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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With