Count the number of occurrences when a string contains a substring

I have a line like

'abbb'

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

grep('bb','abbb')

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

+4
source share
3 answers

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
}))
+3
source

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

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

stri_count

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

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

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

Source: https://habr.com/ru/post/1629949/


All Articles