2012-06-10 159 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"