naitnix
naitnix

Reputation: 35

How can I get the number of times a substring appears in a text

I want to get the number of occurrences of a substring in a text.

fullText = 'aa_bb_cc_dd_eeeee_ff'
substr   = 'ee'

I want to count how many times ee matches aa_bb_cc_dd_eeeee_ff, and the result should be 4.

Upvotes: 2

Views: 85

Answers (2)

Abdo
Abdo

Reputation: 14051

@sawa's solution is more efficient (and general) but if you want to do it without regexes, here's another way:

'aa_bb_cc_dd_eeeee_ff'.chars.each_cons(2).inject(0) { |c, (i,j)| 
    c+=1 if (i == 'e' && i == j); c 
 }

Upvotes: 0

sawa
sawa

Reputation: 168091

'aa_bb_cc_dd_eeeee_ff'.scan(/(?=ee)/).length
# => 4

Upvotes: 5

Related Questions