如何檢查字符串中出現短語的次數?如何計算一個字符串元素在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