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

发布于 2024-10-25 09:19:44 字数 608 浏览 1 评论 0原文

我正在寻找可以帮助我查找字符串中字符出现次数的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挖鼻大婶 2024-11-01 09:19:45

我能够通过 scan 传递一个字符串来解决这个问题,如另一个答案所示。

例如:

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

输出:

2

我还能够通过使用扫描并传递刺痛而不是正则表达式来提取出现的次数,这与另一个答案略有不同,但有助于避免正则表达式。

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

输出:

['e','e']

在我弄清楚之后,我在我创建的视频中进一步探索了这些方法。

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 video I created after I figured it out.

满地尘埃落定 2024-11-01 09:19:44

如果您只想要 a 的数量:

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

Docs 了解更多详情。

If you just want the number of a's:

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

Docs for more details.

挽梦忆笙歌 2024-11-01 09:19:44

之前提出的问题的此链接应该有所帮助
在 Ruby 中扫描字符串

扫描会返回所有出现的字符串字符串中的字符串作为数组,因此

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

将返回

["a","a"]

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"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文