我正在尝试创建一个输入两个字符串的程序。如果它们匹配,则返回它们包含相同长度2子串的位置数。
例如:string_match('xxcaazz','xxbaaz')→3“xx”“aa”“az” 我的问题是我应该使用哪些元字符来验证
这是我的想法
puts "enter word"
a = STDIN.gets
a.chomp!
puts"enter word"
b = STDIN.gets
b.chomp!
if a == /word/ or b == /word/ then
puts str.match(/{a} {b}/) + "equal"
end
答案 0 :(得分:1)
更新的答案:
(仍然飙升,但更好)
first_word = 'xxcaazz'.split('')
second_word ='xxbaaz'.split('')
first_word_length = first_word.length
second_word_length = second_word.length
if [first_word_length, second_word_length].min == first_word_length
inner_word = second_word
outter_word = first_word
else
inner_word = first_word
outter_word = second_word
end
outter_word_length = outter_word.length - 2
word_matches = 0
(0..outter_word_length).each do |character|
if "#{outter_word[character]}#{outter_word[character + 1]}" == "#{inner_word[character]}#{inner_word[character + 1]}"
puts "#{outter_word[character]}#{outter_word[character + 1]}"
word_matches += 1
end
end
puts "Found #{word_matches} matches"
原始SPIKE:
这可能会让你有一个良好的开端(虽然它绝不是防弹,只是一个快速的飙升):
first_word = 'xxcaazz'.split('')
second_word ='xxbaaz'.split('')
first_word_length = first_word.length
(0..first_word_length).each do |character|
if "#{second_word[character]}#{second_word[character + 1]}" == "#{first_word[character]}#{first_word[character + 1]}"
puts "#{second_word[character]}#{second_word[character + 1]}"
end
end
答案 1 :(得分:1)
解包'a2X'表示提取2个字节,然后倒回1个字节:
first_word = 'xxcaazz'
second_word ='xxbaaz'
tokens = first_word.unpack 'a2X' * (first_word.length - 1)
# => ["xx", "xc", "ca", "aa", "az", "zz"]
tokens.flat_map{|m| second_word.scan m}
# => ["xx", "aa", "az"]