Reputation: 53
a <- "ABDBBBLKDLKFFABDBOKKKMXKMABDBLPDLABDBKMKNABDBLKMXLSKMABDBOKOLKABDB"
How to find how many times "ABDB" is repeated in a string?
Upvotes: 0
Views: 112
Reputation: 23788
Here is a solution that neither requires a loop over the string nor an external package:
length(unlist(strsplit(paste0(a, "#"), "ABDB"))) - 1
#[1] 7
In this line of code, "#"
is an auxiliary delimiter that is temporarily attached at the end of the string to make sure that occurrences of the pattern at the end are accounted for correctly.
Upvotes: 3
Reputation: 99331
stringi
can do this very easily.
library(stringi)
stri_count_fixed(a, "ABDB")
# [1] 7
Upvotes: 4