Let's say I have a string, like string= "aasmflathesorcerersnstonedksaottersapldrrysaahf"
. If you haven't noticed, you can find the phrase "harry potter and the sorcerers stone"
in there (minus the space).
I need to check whether string
contains all the elements of the string.
string.include? ("sorcerer") #=> true
string.include? ("harrypotterandtheasorcerersstone") #=> false, even though it contains all the letters to spell harrypotterandthesorcerersstone
Include does not work on shuffled string.
How can I check if a string contains all the elements of another string?
You can use the String class's =~ method with the regex /\d/ as the argument.
Accessing Characters Within a String To print or work with some of the characters in a string, use the slice method to get the part you'd like. Like arrays, where each element corresponds to an index number, each of a string's characters also correspond to an index number, starting with the index number 0.
chars is a String class method in Ruby which is used to return an array of characters in str. Returns: An array of the characters.
Sets and array intersection don't account for repeated chars, but a histogram / frequency counter does:
require 'facets'
s1 = "aasmflathesorcerersnstonedksaottersapldrrysaahf"
s2 = "harrypotterandtheasorcerersstone"
freq1 = s1.chars.frequency
freq2 = s2.chars.frequency
freq2.all? { |char2, count2| freq1[char2] >= count2 }
#=> true
Write your own Array#frequency
if you don't want to the facets dependency.
class Array
def frequency
Hash.new(0).tap { |counts| each { |v| counts[v] += 1 } }
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With