35
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで文字列(二文字以上)の出現回数を数える

Posted at

はじめに

こんな文字列があるぞ!この中にrubyって何個あるんだ?

s = 'rubyruborubyrubkrubarubyrubi'

こんなのcountで一発だな!

countを使ってみる

s = 'rubyruborubyrubkkrubaarubyruba'
p s.count('r')
# => 7

なるほど。rは7個あるらしい。

s = 'rubyruborubyrubkkrubaarubyruba'
p s.count('ruby')
# => 24

絶対24個もないでしょ!!!

countだと複数文字をカウントできない

上記の例だと、r,u,b,y のどれかにマッチする文字の個数をカウントしてしまっている。
つまりcountで複数文字を数えることはできないのだ。

scanを使おう

一致する文字列を抽出して配列にするというscanというメソッドを使おう。

s = 'rubyruborubyrubkkrubaarubyruba'
p s.scan('ruby')
# => ["ruby", "ruby", "ruby"]

p s.scan('ruby').length
# => 3

複数文字のカウントができた〜!

35
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?