代码之家  ›  专栏  ›  技术社区  ›  michaelmichael

每X个字符插入一个不带正则表达式的东西

  •  1
  • michaelmichael  · 技术社区  · 15 年前

    this 问题是,询问者请求一个解决方案,即每x个字符插入一个空格。答案都涉及到使用正则表达式。如果没有正则表达式,您将如何实现这一点?

    这是我想出来的,但有点多。还有更简洁的解决方案吗?

    string = "12345678123456781234567812345678"
    new_string = string.each_char.map.with_index {|c,i| if (i+1) % 8 == 0; "#{c} "; else c; end}.join.strip
    => "12345678 12345678 12345678 12345678"
    
    3 回复  |  直到 8 年前
        1
  •  3
  •   Jörg W Mittag    15 年前
    class String
      def in_groups_of(n)
        chars.each_slice(n).map(&:join).join(' ')
      end
    end
    
    '12345678123456781234567812345678'.in_groups_of(8)
    # => '12345678 12345678 12345678 12345678'
    
        2
  •  0
  •   Adrian    15 年前
    class Array
      # This method is from
      # The Poignant Guide to Ruby:
      def /(n)
        r = []
        each_with_index do |x, i|
          r << [] if i % n == 0
          r.last << x
        end
        r
      end
    end
    
    s = '1234567890'
    n = 3
    join_str = ' '
    
    (s.split('') / n).map {|x| x.join('') }.join(join_str)
    #=> "123 456 789 0"
    
        3
  •  -1
  •   Alex Korban    15 年前

    这稍微短一些,但需要两行:

    new_string = ""
    s.split(//).each_slice(8) { |a| new_string += a.join + " " }
    
    推荐文章