Find all possible substrings of length n

后端 未结 2 771
予麋鹿
予麋鹿 2020-12-19 13:26

I have an interesting (only for me, perhaps, :)) question. I have text like:

\"abbba\"

The question is to find all possible substrings of

2条回答
  •  时光说笑
    2020-12-19 13:58

    We may use

    x <- "abbba"
    allsubstr <- function(x, n) unique(substring(x, 1:(nchar(x) - n + 1), n:nchar(x)))
    allsubstr(x, 2)
    # [1] "ab" "bb" "ba"
    allsubstr(x, 3)
    # [1] "abb" "bbb" "bba"
    

    where substring extracts a substring from x starting and ending at specified positions. We exploit the fact that substring is vectorized and pass 1:(nchar(x) - n + 1) as starting positions and n:nchar(x) as ending positions.

提交回复
热议问题