假设我有一个字符串,例如 string= "aasmflathesorcerersnstonedksaottersapldrrysaahf"
。如果您没有注意到,您可以在其中找到短语 "harry potter and the sorcerers stone"
(减去空格)。
我需要检查 string
是否包含字符串的所有元素。
string.include? ("sorcerer") #=> true
string.include? ("harrypotterandtheasorcerersstone") #=> false, even though it contains all the letters to spell harrypotterandthesorcerersstone
Include 不适用于打乱的字符串。
如何检查一个字符串是否包含另一个字符串的所有元素?
最佳答案
集合和数组交集不考虑重复的字符,但是 histogram / frequency counter做:
require 'facets'
s1 = "aasmflathesorcerersnstonedksaottersapldrrysaahf"
s2 = "harrypotterandtheasorcerersstone"
freq1 = s1.chars.frequency
freq2 = s2.chars.frequency
freq2.all? { |char2, count2| freq1[char2] >= count2 }
#=> true
如果您不想依赖方面,请编写您自己的Array#frequency
。
class Array
def frequency
Hash.new(0).tap { |counts| each { |v| counts[v] += 1 } }
end
end
关于ruby - 检查一个字符串是否包含 Ruby 中另一个字符串的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39212786/