Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
506 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...