I'm looking for the Ruby method (1.9...) that can help me find the number of occurrences of a character in a string. I'm looking for all occurrences, not only the first one.
我正在寻找Ruby方法(1.9…),它可以帮助我找到字符串中出现字符的数量。我在寻找所有的事件,不仅仅是第一个。
For example: "Melanie is a noob" There are two occurrences of the letter 'a'. What would be the Ruby method I could use in order to find this?
例如:“Melanie is a noob”有两个字母“a”。为了找到这个,我可以使用什么Ruby方法呢?
I've been using Ruby-doc.org as a reference and the scan method in the String class, in particular, caught my eye. However, the wording is a bit difficult for me, so I don't really grasp the concept of scan.
我一直在使用Ruby-doc.org作为参考,特别是String类中的扫描方法引起了我的注意。但是,我的用词有点困难,所以我没有真正理解扫描的概念。
3 个解决方案
#1
126
If you just want the number of a's:
如果你只想要a的数目:
puts "Melanie is a noob".count('a') #=> 2
#2
49
This link from a question asked previously should help scanning a string in Ruby
这个来自前面问题的链接应该有助于扫描Ruby中的字符串
scan returns all the occurrences of a string in a string as an array, so
扫描返回字符串中出现的所有字符串作为数组,因此
"Melanie is a noob".scan(/a/)
will return
将返回
["a","a"]
#3
28
You're looking for the String.index()
method:
您正在寻找String.index()方法:
Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
返回str中给定子字符串或模式(regexp)第一次出现的索引。如果没有找到则返回nil。如果第二个参数存在,它将指定字符串中开始搜索的位置。
"hello".index('e') #=> 1 "hello".index('lo') #=> 3 "hello".index('a') #=> nil "hello".index(?e) #=> 1 "hello".index(/[aeiou]/, -3) #=> 4
#1
126
If you just want the number of a's:
如果你只想要a的数目:
puts "Melanie is a noob".count('a') #=> 2
#2
49
This link from a question asked previously should help scanning a string in Ruby
这个来自前面问题的链接应该有助于扫描Ruby中的字符串
scan returns all the occurrences of a string in a string as an array, so
扫描返回字符串中出现的所有字符串作为数组,因此
"Melanie is a noob".scan(/a/)
will return
将返回
["a","a"]
#3
28
You're looking for the String.index()
method:
您正在寻找String.index()方法:
Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
返回str中给定子字符串或模式(regexp)第一次出现的索引。如果没有找到则返回nil。如果第二个参数存在,它将指定字符串中开始搜索的位置。
"hello".index('e') #=> 1 "hello".index('lo') #=> 3 "hello".index('a') #=> nil "hello".index(?e) #=> 1 "hello".index(/[aeiou]/, -3) #=> 4