LoginSignup
0
0

More than 1 year has passed since last update.

特定の文字列の数をカウントする方法

Last updated at Posted at 2022-10-01

概要

特定の文字列の数をカウントする方法を備忘録として残します。

はじめに

scanメソッドとlengthメソッドを活用します。まずは復習から。

scanメソッドとは?

対象の文字列の中に特定の文字列の検索結果を配列として返します。

"foobarbazfoobarbaz".scan("ba")
# => ["ba", "ba", "ba", "ba"]

lengthメソッドとは?

文字列の文字数を返します。

def count_hi(str)
  puts str.length
end
count_hi('abc hi ho') #=> 9

ん??それだと、今回の文字列の数をカウントするには使えない?

文字列の数(要素数)をカウントするには?

lengthメソッドにはstringクラスの他にも、arrayクラスにもあります。
上記のカウント方法は、stringクラスで取得したものです。
今回はarrayクラスを活用して要素数を取得します。

array = ["abc hi ho","hihi","efgh"]
puts array.length #=> 3

無事に要素の数を取得することができました。

よって、以下のように記述し、特定の文字列の数をカウントすることができました。

def count_ba(str)
  puts str.scan("ba").length
end

count_ba("foobarbazfoobarbaz") #=>4

参考

scanメソッド:公式リファレンス
lengthメソッド:公式リファレンス

0
0
2

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
0
0