开发者

Split a string into an array based on runs of contiguous characters

I've been searching for an answer to this in Ruby for a little while now and haven't found a good solution. What I am trying to figure out is how to split a string when the next character doesn't match the previous and pass the groupings into an array. ie.

'aaaabbbbzzxxxhhnnppp'

becomes

['aaaa', 'bb开发者_C百科bb', 'zz', 'xxx', 'hh', 'nn', 'ppp']

I know I could just iterate over each char in the string and check for a change but am curious if there's anything built-in that could tackle this in a elegant manner.


Doable with a simple regex:

'aaaabbbbzzxxxhhnnppp'.scan(/((.)\2*)/).map{|x| x[0]}
=> ["aaaa", "bbbb", "zz", "xxx", "hh", "nn", "ppp"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜