简体   繁体   中英

Finding # occurrences of a character in a string in Ruby

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 just the first one.

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?

I've been using Ruby-doc.org as a reference and the scan method in the String: class caught my eye. The wording is a bit difficult for me to understand, so I don't really grasp the concept of scan .

Edit: I was able to solve this using scan . I shared in a video how I achieved it.

If you just want the number of a's:

puts "Melanie is a noob".count('a')  #=> 2

Docs for more details.

This link from a question asked previously should help scanning a string in 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"]

You're looking for the String.index() method:

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.

 "hello".index('e') #=> 1 "hello".index('lo') #=> 3 "hello".index('a') #=> nil "hello".index(?e) #=> 1 "hello".index(/[aeiou]/, -3) #=> 4 

I was able to solve this by passing a string through scan as shown in another answer.

For example:

string = 'This is an example'
puts string.count('e')

Outputs:

2

I was also able to pull the occurrences by using scan and passing a sting through instead of regex which varies slightly from another answer but was helpful in order to avoid regex.

string = 'This is an example'
puts string.scan('e')

Outputs:

['e','e']

I explored these methods further in a small video guide I created after I figured it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM