Ruby: How to count the number of times a string appears in another string?

前端 未结 3 1712
轻奢々
轻奢々 2021-02-01 12:07

I\'m trying to count the number of times a string appears in another string.

I know you can count the number of times a letter appears in a string:

strin         


        
3条回答
  •  不思量自难忘°
    2021-02-01 12:49

    It's because the count counts characters, not instances of strings. In this case 'aa' means the same thing as 'a', it's considered a set of characters to count.

    To count the number of times aa appears in the string:

    string = "aabbccddbb"
    string.scan(/aa/).length
    # => 1
    string.scan(/bb/).length
    # => 2
    string.scan(/ff/).length
    # => 0
    

提交回复
热议问题