Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding common string in array of strings (ruby)

Tags:

ruby

Given I have an array of 3 strings:

["Extra tv in bedroom",
 "Extra tv in living room",
 "Extra tv outside the shop"]

How do I find the longest string all strings have in common?

like image 709
Jesper Rønn-Jensen Avatar asked Jan 28 '10 22:01

Jesper Rønn-Jensen


People also ask

How do you join an array of strings in Ruby?

When you want to concatenate array elements with a string, you can use the array. join() method or * operator for this purpose. For this shot, we will be using the * operator to concatenate elements of an array with a string.

How do you find the part of a string in Ruby?

Accessing Characters Within a String To print or work with some of the characters in a string, use the slice method to get the part you'd like. Like arrays, where each element corresponds to an index number, each of a string's characters also correspond to an index number, starting with the index number 0.


2 Answers

Here's a rubyish way of doing it. You should use a more advanced algorithm if you have a bunch of strings or they are very long, though:

def longest_common_substr(strings)
  shortest = strings.min_by &:length
  maxlen = shortest.length
  maxlen.downto(0) do |len|
    0.upto(maxlen - len) do |start|
      substr = shortest[start,len]
      return substr if strings.all?{|str| str.include? substr }
    end
  end
end

puts longest_common_substr(["Extra tv in bedroom",
                            "Extra tv in living room",
                            "Extra tv outside the shop"])
like image 93
mckeed Avatar answered Sep 24 '22 17:09

mckeed


If you want to search for the beginning of all strings:

Source

def substr( a )
    return "" unless (a.length > 0)
    result = 0
    (0 ... a.first.length).each do |k|
        all_matched = true
        character = a.first[k]
        a.each{ |str| all_matched &= (character == str[k]) }
        break unless all_matched
        result+=1
    end
    a.first.slice(0,result)
end

Test

input = ["Extra tv in bedroom",
 "Extra tv in living room",
 "Extra tv outside the shop"]

puts substr( input ) + "."

Output

Extra tv .
like image 32
St.Woland Avatar answered Sep 22 '22 17:09

St.Woland