在 Ruby 中查找字符串中某个字符的 # 次出现
我正在寻找可以帮助我查找字符串中字符出现次数的 Ruby 方法 (1.9...)。我正在寻找所有发生的情况,而不仅仅是第一个。
例如:“梅兰妮是个菜鸟” 字母“a”出现两次。 我可以使用什么 Ruby 方法来找到这个?
我一直在使用 Ruby-doc.org 作为参考和 scan
方法String: class
引起了我的注意。这个措辞对我来说有点难以理解,所以我并没有真正掌握scan
的概念。
编辑:我能够使用scan
解决这个问题。 我在视频中分享了一些解决方案和文章分享如何做到这一点。
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 a few solutions in a video and article sharing how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我能够通过
scan
传递一个字符串来解决这个问题,如另一个答案所示。例如:
输出:
我还能够通过使用扫描并传递刺痛而不是正则表达式来提取出现的次数,这与另一个答案略有不同,但有助于避免正则表达式。
输出:
在我弄清楚之后,我在我创建的视频中进一步探索了这些方法。
I was able to solve this by passing a string through
scan
as shown in another answer.For example:
Outputs:
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.
Outputs:
I explored these methods further in a video I created after I figured it out.
如果您只想要 a 的数量:
Docs 了解更多详情。
If you just want the number of a's:
Docs for more details.
之前提出的问题的此链接应该有所帮助
在 Ruby 中扫描字符串
扫描会返回所有出现的字符串字符串中的字符串作为数组,因此
将返回
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
will return