计算一个字符串在另一个字符串中出现的次数(Perl) [英] Counting number of occurrences of a string inside another (Perl)

查看:74
本文介绍了计算一个字符串在另一个字符串中出现的次数(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.

推荐答案

您可以捕获字符串,然后对其进行计数.可以通过使用 () 将列表上下文应用于捕获来完成:

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;

这篇关于计算一个字符串在另一个字符串中出现的次数(Perl)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆