Count the number of overlapping substrings within a string

r, string

Solution

I believe that

find_overlaps <- function(p,s) {
    gg <- gregexpr(paste0("(?=",p,")"),s,perl=TRUE)[[1]]
    if (length(gg)==1 && gg==-1) 0 else length(gg)
}


find_overlaps("aa","aaabaabaa")  ## 4
find_overlaps("not_there","aaabaabaa") ## 0 
find_overlaps("aa","aaaaaaaa")  ## 7

will do what you want, which would be more clearly expressed as "finding the number of overlapping substrings within a string".

This a minor variation on Finding the indexes of multiple/overlapping matching substrings

Problem

example: ``` s <- "aaabaabaa" p <- "aa" ``` I want to return 4, not 3 (i.e. counting the number of `"aa"` instances in the initial `"aaa"` as 2, not 1). Is there any package to solve it? Or is there any way to count in R?

Original source

Related problems