2012-06-10 111 views
0

给出两个字符串,如下所示,我想合并它们以生成以下内容。结果变得毫无意义,但是,这两个字符串的共同点“的句子”,这是因为这两个字符串之间的连接器什么罪名:Ruby函数将两个字符串合并为一个

"This is a sentence is a great thing" 

s1 = "This is a sentence" 

s2 = "a sentence is a great thing" 

是否有红宝石这个功能?

+0

char或字处理水平? – tokland

回答

1

这是一个可行的解决方案。

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

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

您可能必须为此编写一个自己的函数。简单的在输入长度中以二次方式运行。但是,通过使用this algorithm,可以在输入大小的线性时间内执行此操作。

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" 
+0

-1用于for循环。开玩笑。尽管如此。 – pguardiario

+0

for循环在这种情况下是最好的))... ...我不知道为什么做到这一点)) –

+0

例如1.upto在这种情况下更好,因为它不污染主要范围。 (1 .. [length,str.length] .min)。每个可能是最好的,因为它是最常见的。 – pguardiario

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"