简体   繁体   中英

Splitting string into pair of characters in Ruby

我有一个字符串(例如“AABBCCDDEEFF”)并希望将其拆分为一个数组,每个元素包含两个字符 - [“AA”,“BB”,“CC”,“DD”,“EE”,“FF”] 。

Try the String object's scan method:

>> foo = "AABBCCDDEEFF"
=> "AABBCCDDEEFF"
>> foo.scan(/../)
=> ["AA", "BB", "CC", "DD", "EE", "FF"]

Depending on your needs, this may work better:

>  foo = "AAABBCDEEFF"
=> "AAABBCDEEFF"
> foo.scan(/.{1,2}/)
=> ["AA", "AB", "BC", "DE", "EF", "F"]

Not sure what your input looks like. The above answer will drop any characters that do not have a pair, this one will work on odd length strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM