Ruby函数将两个字符串合并为一个

时间:2012-06-10 08:27:36

标签: ruby-on-rails ruby

给出两个类似下面的字符串,我想合并它们以生成以下内容。结果没有多大意义,但是,两个字符串都有一个共同的“句子”,这就是两个字符串之间的连接符:

"This is a sentence is a great thing"

s1 = "This is a sentence" 

s2 = "a sentence is a great thing"

红宝石中有这个功能吗?

4 个答案:

答案 0 :(得分:2)

这是一个有效的解决方案。

def str_with_overlap(s1, s2)
  result = nil
  (0...(s2.length)).each do |idx|
    break result = s1 + s2[(idx + 1)..-1] if s1.end_with?(s2[0..idx])
  end
  result
end

str_with_overlap("This is a sentence", "a sentence is a great thing")
# => This is a sentence is a great thing

答案 1 :(得分:1)

据我所知,Ruby中没有内置函数。

您可能必须为此编写自己的函数。直接的一个在输入长度的二次时间内运行。但是,可以使用this algorithm在输入大小的线性时间内完成此操作。

答案 2 :(得分:1)

Ruby中没有内置方法,但你可以试试这个

class String
  def merge str
    result = self + str
    for i in 1..[length,str.length].min
      result = self[0,length-i] + str if self[-i,i] == str[0,i]
    end
    result
  end
end

"This is a sentence".merge "a sentence is a great thing"

答案 3 :(得分:0)

功能方法(在单词级别工作):

ws1, ws2 = [s1, s2].map(&:split)
idx = 0.upto(ws1.size-1).detect { |i| ws1[i..-1] == ws2[0, ws1.size-i] } || 0
(ws1[0, ws1.size-idx] + ws2).join(" ")
=> "This is a sentence is a great thing"