【问题标题】:Ruby function to merge two string into oneRuby函数将两个字符串合并为一个
【发布时间】:2012-06-10 08:27:36
【问题描述】:

给定两个类似下面的字符串,我想将它们合并以生成以下内容。结果没有什么意义,但是,两个字符串都有一个共同的“句子”,这就是两个字符串之间的连接符:

"This is a sentence is a great thing"

s1 = "This is a sentence" 

s2 = "a sentence is a great thing"

在 ruby​​ 中有这个功能吗?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      您可能必须为此编写一个自己的函数。直接的一个在输入长度上以二次时间运行。但是,可以使用this algorithm 在输入大小的线性时间内完成。

      【讨论】:

        【解决方案3】:

        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"
        

        【讨论】:

        • for 循环在这种情况下是最好的))...我不知道你为什么要这样做))
        • 例如 1.upto 在这种情况下更好,因为它不会污染主范围。 (1..[length,str.length].min).each 可能是最好的,因为它最常见。
        • 本例中的主作用域是函数作用域,所以根本不是问题,但我不得不承认,在我的系统上,每个作用域都快 10%))
        • 10% 不重要,避免for循环的原因是范围问题。
        【解决方案4】:

        函数式方法(在单词级别起作用):

        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"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-14
          • 2011-06-02
          • 2017-10-25
          • 2021-07-23
          • 1970-01-01
          • 2012-05-15
          • 2015-02-05
          相关资源
          最近更新 更多