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

Mel*_*bel 97 ruby string methods

我正在寻找可以帮助我找到字符串中字符出现次数的Ruby方法(1.9 ...).我正在寻找所有事件,而不仅仅是第一个事件.

例如:"Melanie是一个菜鸟"字母'a'有两次出现.我可以用什么Ruby方法来找到它?

我一直在使用Ruby-doc.org作为参考和scan方法String: class引起了我的注意.我的措辞有点难以理解,所以我并没有真正理解这个概念scan.

ste*_*lag 135

如果你只想要a的数量:

puts "Melanie is a noob".count('a')  #=> 2
Run Code Online (Sandbox Code Playgroud)

文档了解更多详情.

  • 我真的*喜欢这个答案,直到我注意到你刚从问题中取出字符串:-)但仍然是+1. (16认同)
  • @Gediminas`count`计算字符,而不是字符串."voyage.localhost.com".count('www.')与"voyage.localhost.com".count('w.')相同,因为没有w和两个点,结果为2. (12认同)
  • 你有没有机会添加[链接到文档](http://ruby-doc.org/core-2.3.0/String.html#method-i-count)? (2认同)
  • 我最初对这个答案感到非常震惊,然后我看到Melanie首先使用了这个例子.好答案! (2认同)

Shi*_*hiv 50

来自之前提出的问题的这个链接应该有助于 扫描Ruby中的字符串

scan将字符串中所有出现的字符串作为数组返回,所以

"Melanie is a noob".scan(/a/)
Run Code Online (Sandbox Code Playgroud)

将返回

["a","a"]
Run Code Online (Sandbox Code Playgroud)

  • `scan`也适用于简单的字符串,因此`scan('a')`也可以使用 (3认同)

Geo*_*lly 30

你正在寻找String.index()方法:

返回str中给定子字符串或模式(regexp)的第一次出现的索引.如果找不到则返回nil.如果存在第二个参数,则它指定字符串中开始搜索的位置.

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

  • 从来不知道你可以在代码块中嵌入代码!整齐 (3认同)

Mel*_*bel 2

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

例如:

string = 'This is an example'
puts string.count('e')
Run Code Online (Sandbox Code Playgroud)

输出:

2
Run Code Online (Sandbox Code Playgroud)

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

string = 'This is an example'
puts string.scan('e')
Run Code Online (Sandbox Code Playgroud)

输出:

['e','e']
Run Code Online (Sandbox Code Playgroud)

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