Ruby - 计算字符串在另一个字符串中出现的次数? [英] Ruby - Count the number of times a string appears in another string?

查看:594
本文介绍了Ruby - 计算字符串在另一个字符串中出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算字符串在另一个字符串中出现的次数

I'm trying to count the number of times a string appears in another string

我知道你可以计算一个字母在字符串中出现的次数

I know you can count the number of times a letter appears in a string

string="aabbccddbb"
string.count('a')
=> 2

但是如果我搜索多少次'aa'出现在这个字符串中, 。

But if I search for how many times 'aa' appears in this string, I also get two.

string.count('aa')
=> 2

我不明白这一点。

推荐答案

我将这个值放在引号中,所以我正在搜索确切的字符串出现的次数,而不仅仅是字母。

这里有几种方法来计算字符串中出现的给定子字符串的次数(第一个是我的首选项)。注意(由OP确认),子串'aa'在字符串'aaa'中出现两次,因此五次在:

Here are a couple of ways to count the numbers of times a given substring appears in a string (the first being my preference). Note (as confirmed by the OP) the substring 'aa' appears twice in the string 'aaa', and therefore five times in:

string="aaabbccaaaaddbb"

#1

使用 String#scan ,其中正则表达式包含查找子字符串的正前瞻:

Use String#scan with a regex that contains a positive lookahead that looks for the substring:

def count_em(string, substring)
  string.scan(/(?=#{substring})/).count
end

count_em(string,"aa")
 #=> 5

注意:

"aaabbccaaaaddbb".scan(/(?=aa)/)
  #=> ["", "", "", "", ""]

相同的结果:

"aaabbccaaaaddbb".scan(/(?<=aa)/)
  #=> ["", "", "", "", ""]

#2

转换为数组,应用 Enumerable#each_cons ,then join and count:

Convert to an array, apply Enumerable#each_cons, then join and count:

def count_em(string, substring)
  string.each_char.each_cons(substring.size).map(&:join).count(substring)
end

count_em(string,"aa")
  #=> 5

我们有:

enum0 = "aaabbccaaaaddbb".each_char
  #=> #<Enumerator: "aaabbccaaaaddbb":each_char>

我们可以看到这个枚举器生成的元素转换为数组:

We can see the elements that will generated by this enumerator by converting it to an array:

enum0.to_a
  #=> ["a", "a", "a", "b", "b", "c", "c", "a", "a", "a",
  #    "a", "d", "d", "b", "b"]

enum1 = enum0.each_cons("aa".size)
  #=> #<Enumerator: #<Enumerator: "aaabbccaaaaddbb":each_char>:each_cons(2)> 

转换 enum1 枚举器将传递的值 map

Convert enum1 to an array to see what values the enumerator will pass on to map:

enum1.to_a
  #=> [["a", "a"], ["a", "a"], ["a", "b"], ["b", "b"], ["b", "c"],
  #    ["c", "c"], ["c", "a"], ["a", "a"], ["a", "a"], ["a", "a"], 
  #    ["a", "d"], ["d", "d"], ["d", "b"], ["b", "b"]]

c = enum1.map(&:join)
  #=> ["aa", "aa", "ab", "bb", "bc", "cc", "ca",
  #    "aa", "aa", "aa", "ad", "dd", "db", "bb"]
c.count("aa")
  #=> 5

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

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