Ruby在不使用正则表达式的序列中计算字符 [英] Ruby Counting chars in a sequence not using regex
本文介绍了Ruby在不使用正则表达式的序列中计算字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码在计数序列中的字符数方面需要帮助。
Need help with this code on counting chars in a sequence.
这就是我想要的:
word("aaabbcbbaaa") == [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]
word("aaaaaaaaaa") == [["a", 10]]
word("") == []
这是我的代码:
def word(str)
words=str.split("")
count = Hash.new(0)
words.map {|char| count[char] +=1 }
return count
end
我得到了word( aaabbcbbaaa)=> [[ a,6],[ b,4],[ c,1]],这不是我想要的。我想计算每个序列。我更喜欢无正则表达式的解决方案。谢谢。
I got word("aaabbcbbaaa") => [["a", 6], ["b", 4], ["c", 1]], which is not what I want. I want to count each sequence. I prefer a none regex solution. Thanks.
推荐答案
按字符分割字符串,然后按字符分组,然后按块计数字符:
Split string by chars, then group chunks by char, then count chars in chunks:
def word str
str
.chars
.chunk{ |e| e }
.map{|(e,ar)| [e, ar.length] }
end
p word "aaabbcbbaaa"
p word("aaaaaaaaaa")
p word ""
结果:
[["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]
[["a", 10]]
[]
这篇关于Ruby在不使用正则表达式的序列中计算字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文