如何检查字符串中出现短语的次数?如何计算一个字符串元素在ruby中另一个字符串中的出现?
例如,让我们说这句话是donut
str1 = "I love donuts!"
#=> returns 1 because "donuts" is found once.
str2 = "Squirrels do love nuts"
#=> also returns 1 because of 'do' and 'nuts' make up donut
str3 = "donuts do stun me"
#=> returns 2 because 'donuts' and 'do stun' has all elements to make 'donuts'
我检查建议使用包括this SO,但如果是为了阐明它才会起作用。
我想出了这个,但它不会停止拼写所有元素"donuts"
拼写。即"I love donuts" #=> ["o", "d", "o", "n", "u", "t", "s"]
def word(arr)
acceptable_word = "donuts".chars
arr.chars.select { |name| acceptable_word.include? name.downcase }
end
如何检查一个给定的字符串中如何许多发生在那里?没有边缘情况。输入将始终为String
,不可为零。如果它包含donut
的元素,则不应将其计为1次;它需要包含,并不是必须的。
http://stackoverflow.com/questions/25938430/ruby-count-the-number-of-times-a-string-appears-in-another-string – Zepplock
的可能重复这个问题* *不是**以上的重复,因为这里''眩晕''匹配''甜甜圈'',例如未请求子串匹配。 – mudasobwa
不重复。虽然不同,我在我的帖子上指出这另一个SO:http://stackoverflow.com/questions/8258517/how-to-check-whether-a-string-contains-a-substring-in-ruby其中“排序“字符串无关紧要。也许“秩序”不是一个好的描述。对困惑感到抱歉!正如@mudasobwa所说,“甜甜圈”和“眩晕”都应该返回匹配。 – Iggy