2009-09-30 5 views
0

rubisen comparant plusieurs chaînes caractère par caractère et en produisant le chevauchement?

j'ai les suivantes

p = 0 
[s1.size,s2.size].max.times { |c| if s1[c] == s2[c]; p = c; else break; end }; 
matched_part = s1[0..p] 

mais je ne sais pas comment je peux cela pour plusieurs chaînes (plus de 2) en même temps.

+1

Pourriez-vous nous donner une entrée exemple et la sortie désirée? – Allyn

+0

Je seconde la question d'Allyn. – khelll

+0

Marry avait un petit agneau avait un chien marier bug avait un chat se marier marier avait un oiseau OUT: Mary avait un –

Répondre

0
class String 
    def self.overlap(first,second,*others) 
    s1 = first 
    others = [second] + others 
    others.each do |s2| 
     p = 0 
     s1.length.times { |c| if s1[c] == s2[c] then p = c else break end } 
     s1 = s1[0..p] 
    end 
    s1 
    end 
end 

puts String.overlap "marry had a little lamb", "marry had a bug dog", "marry had a cat", "marry had a bird OUT:", "marry had something" #=> marry had 
3

D'accord, comment ça?

class String 
    def self.overlap(s1,s2,*strings) 
    strings += [s2] 
    strings.min { |s| s.size }.size.times do |n| 
     return s1[0,n] unless strings.all? { |string| s1[n]==string[n] } 
    end 
    s1 
    end 
end 
+0

+1 pour – khelll

0

en une ligne:

strings[0].slice(0,(0...strings[0].size).find {|i| strings.map {|s| s[i..i]}.uniq.size > 1}) 
+0

Belle concision. Testé avec 2 chaînes et ne fonctionne pas lorsque la première chaîne est entièrement contenue dans le second. Pas un correctif universel je suppose, mais ce qui a fonctionné pour mon cas d'utilisation avec 2 chaînes: strings [0] .slice (0, (0 ... strings [0] .size) .find {| i | strings.map {| s | s [i..i]}. uniq.size> 1} || chaînes [0] .length) – Nico

Questions connexes