简体   繁体   English

在 Ruby 中查找字符串中出现的 # 个字符

[英]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.我正在寻找可以帮助我找到字符串中某个字符出现次数的 Ruby 方法 (1.9 ...)。 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'.例如:“Melanie is a noob” 字母“a”出现了两次。 What would be the Ruby method I could use in order to find this?我可以使用什么 Ruby 方法来找到它?

I've been using Ruby-doc.org as a reference and the scan method in the String: class caught my eye.我一直在使用Ruby-doc.org作为参考, String: classscan方法引起了我的注意。 The wording is a bit difficult for me to understand, so I don't really grasp the concept of scan .措辞对我来说有点难以理解,所以我并没有真正掌握scan的概念。

Edit: I was able to solve this using scan .编辑:我能够使用scan解决这个问题。 I shared in a video how I achieved it.我在视频中分享了我如何实现它的。

If you just want the number of a's:如果您只想要 a 的数量:

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来自先前提出的问题的此链接应该有助于扫描 Ruby 中的字符串

scan returns all the occurrences of a string in a string as an array, so scan 将字符串中所有出现的字符串作为数组返回,因此

"Melanie is a noob".scan(/a/)

will return将返回

["a","a"]

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. 返回str中给定子字符串或模式(regexp)第一次出现的索引。 Returns nil if not found. 如果找不到则返回nil。 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.如另一个答案所示,我能够通过scan传递字符串来解决此问题。

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.我在弄清楚之后创建的一个小视频指南中进一步探索了这些方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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