如何拆分一串数量不均匀的重复字符?红宝石 [英] How to split a string of repeated characters with uneven amounts? Ruby

查看:46
本文介绍了如何拆分一串数量不均匀的重复字符?红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串,例如 "aabbbbccdddeffffgg" 并且我想将字符串拆分成这个数组:["aa", "bbbb", "cc", "ddd", "e", "ffff", "gg"],我该怎么做?

If I have a string such as "aabbbbccdddeffffgg" and I wanted to split the string into this array: ["aa", "bbbb", "cc", "ddd", "e", "ffff", "gg"], how would I go about that?

我知道 string.split/.../ <或者不管你在那里放了多少个周期,但它不考虑弦是否不均匀.我正在处理的问题的重点是取两个字符串,看看一个字符串的一行中是否有三个字符,另一个字符串中的一行是否有两个字符.我试过了

I know of string.split/.../ < or however many period you put there, but it doesn't account for if the strings are uneven. The point of the problem I'm working on is to take two strings and see if there are three characters in a row of one string and two in a row in the other. I tried

  `letter_count_1 = {}
    str1.each_char do |let|
       letter_count_1[let] = str1.count(let)
    end`

但这给出了字符串中每个字符总数的计数,并且一些输入在多个位置随机使用相同的字母,例如,"aabbbacccdba"

But that gives the count for the total amount of each character in the string, and some of the inputs are randomized with the same letter in multiple places, like, "aabbbacccdba"

那么如何按字符拆分字符串?

So how do you split the string up by character?

推荐答案

您可以使用带有反向引用和 scan() 方法的正则表达式:

You can use a regex with a back reference and the scan() method:

str = "aabbbbccdddeffffgg"
groups = []
str.scan(/((.)\2*)/) { |x| groups.push(x[0]) }

groups 之后看起来像这样:

["aa", "bbbb", "cc", "ddd", "e", "ffff", "gg"]

这篇关于如何拆分一串数量不均匀的重复字符?红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆