1

我正在尝试创建一个输入两个字符串的程序。如果它们匹配,则返回它们包含相同长度 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
4

2 回答 2

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"

原始尖峰:

这可能会让您有一个良好的开端(尽管它绝不是防弹的,只是一个快速的峰值):

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
于 2012-04-29T23:36:11.967 回答
1

Unpack '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"]
于 2012-04-30T00:46:46.287 回答