Andrea McKenzie
Andrea McKenzie

Reputation: 239

How to split a string of repeated characters with uneven amounts? Ruby

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?

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`

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?

Upvotes: 3

Views: 1502

Answers (2)

hirolau
hirolau

Reputation: 13911

Here is a non-regexp version

str = "aabbbbccdddeffffgg"
p str.chars.chunk(&:itself).map{|x|x.last.join} #=> ["aa", "bbbb", "cc", "ddd", "e", "ffff", "gg"]

Upvotes: 4

hek2mgl
hek2mgl

Reputation: 158060

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 will look like this afterwards:

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

Upvotes: 4

Related Questions