[英]Finding # occurrences of a character in a string in Ruby
我正在尋找可以幫助我找到字符串中某個字符出現次數的 Ruby 方法 (1.9 ...)。 我正在尋找所有事件,而不僅僅是第一個。
例如:“Melanie is a noob” 字母“a”出現了兩次。 我可以使用什么 Ruby 方法來找到它?
我一直在使用Ruby-doc.org作為參考, String: class
的scan
方法引起了我的注意。 措辭對我來說有點難以理解,所以我並沒有真正掌握scan
的概念。
來自先前提出的問題的此鏈接應該有助於掃描 Ruby 中的字符串
scan 將字符串中所有出現的字符串作為數組返回,因此
"Melanie is a noob".scan(/a/)
將返回
["a","a"]
您正在尋找String.index()
方法:
返回str中給定子字符串或模式(regexp)第一次出現的索引。 如果找不到則返回nil。 如果存在第二個參數,則它指定字符串中開始搜索的位置。
"hello".index('e') #=> 1 "hello".index('lo') #=> 3 "hello".index('a') #=> nil "hello".index(?e) #=> 1 "hello".index(/[aeiou]/, -3) #=> 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.