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?
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.
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.
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"])
If you want to search for the beginning of all strings:
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
input = ["Extra tv in bedroom",
"Extra tv in living room",
"Extra tv outside the shop"]
puts substr( input ) + "."
Extra tv .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With