从字符串中获取n个字符

时间:2016-07-01 10:35:17

标签: ruby

我想找到迭代字符串并从中获取每个字符的方法。结果应该类似于数组的each_cons方法。

您现在关于一些现有方法或如何实现自己的方法吗?

3 个答案:

答案 0 :(得分:2)

使用String#each_char

"abcdef".each_char.each_cons(3) { |a| p a }
["a", "b", "c"]
["b", "c", "d"]
["c", "d", "e"]
["d", "e", "f"]
=> nil

答案 1 :(得分:1)

如果你想要"连续字符串"长度3:

r = /
    (?=       # begin a positive lookahead
      ((.{3}) # match any three characters in capture group 1
    )         # close the positive lookahead
    /x        # free-spacing regex definition mode

"abcdef".scan(r).flatten
  #=> ["abc", "bcd", "cde", "def"]

以传统方式编写,这个正则表达式是:

r = /(?=(.{3}))/

如果你想要一个包含三个字母的数组,请执行以下操作:

"abcdef".scan(/(?=(.{3}))/).flatten.map { |s| s.split('') }
  #=> [["a", "b", "c"], ["b", "c", "d"], ["c", "d", "e"], ["d", "e", "f"]] 

答案 2 :(得分:0)

补充其他答案。

"abcdef".each_char.to_a.in_groups_of(3)