LoginSignup
0
0

More than 1 year has passed since last update.

文字数を算出するプログラムの実装

Posted at

問題

以下の要件を満たすcount_hiメソッドを実装しましょう。

対象となる文字列の中から、"hi"という特定の文字列の数を取得する
上記で取得した数を出力する

雛形

def count_hi(str)
  #  処理を記述
end

# 呼び出し例(引数には対象となる文字列を指定します)
count_hi('abc hi ho')

この問題の解き方

対象の文字列の中に"hi"という文字列がいくつあるか数える為、scanメソッドを使用します。
scanメソッドは、対象の要素から引数で指定した文字列を数え、配列として返すメソッドです。

count_hiメソッドの仮引数strには文字列が格納されているので、以下のように記述することで、”hi”という文字列の数だけ配列の要素を返すことができます。

def count_hi(str)
  str.scan("hi")
end

そして、その配列の中の要素の数をlengthメソッドで返し、putsメソッドで出力すれば完成です。

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