Lionir
Lionir

Reputation: 341

Count number of occurrences when string contains substring

I have string like

'abbb'

I need to understand how many times I can find substring 'bb'.

grep('bb','abbb')

returns 1. Therefore, the answer is 2 (a-bb and ab-bb). How can I count number of occurrences the way I need?

Upvotes: 4

Views: 2078

Answers (3)

akrun
akrun

Reputation: 886938

We can use stri_count

library(stringi)
stri_count_regex(input, '(?=bb)')
#[1] 2

stri_count_regex(x, '(?=bb)')
#[1] 0 1 0

data

input <- "abbb"
x <- c('aa','bb','ba')

Upvotes: 1

Pierre L
Pierre L

Reputation: 28441

You can make the pattern non-consuming with '(?=bb)', as in:

length(gregexpr('(?=bb)', x, perl=TRUE)[[1]])
[1] 2

Upvotes: 7

Heroka
Heroka

Reputation: 13139

Here is an ugly approach using substr and sapply:

input <- "abbb"

search <- "bb"


res <- sum(sapply(1:(nchar(input)-nchar(search)+1),function(i){
  substr(input,i,i+(nchar(search)-1))==search
}))

Upvotes: 3

Related Questions