LoginSignup
0
1

More than 3 years have passed since last update.

文字列が左から何文字目に出てくるかを調べたい

Posted at

任意の文字列の中から"get"が左から何文字目に出てくるか調べて、その数を出力したいと思います。

出力例は、

count_code("getexxcode")
 =>1
count_code("aaagetbbb")
=> 4
count_code("cozexxget")
=> 7

indexメソッドを使ってメソッドを作ります。
参考:
Ruby 3.0.0 リファレンスマニュアル:indexメソッド

使用例:

str.index(検索したい文字列, 検索を開始する位置)

初めにメソッドを作成します。

def count_code(str)

end

その中にindexメソッドを使って出力例のように出力したいと思います。

def count_code(str)
  puts str.index("get", 0 )
end

これで、出力することができました。
しかしこのままでは出力例のようにならず、以下の結果となってしまいます。

count_code("getexxcode")
 => 0
count_code("aaagetbbb")
=> 3
count_code("cozexxget")
=> 6

最後に、

def count_code(str)
  puts str.index("get", 0 ) + 1
end

としてあげることで出力例のようになります。

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