R: find largest common substring starting at the beginning

后端 未结 11 2695
星月不相逢
星月不相逢 2021-02-19 18:33

I\'ve got 2 vectors:

word1 <- \"bestelling\"   
word2 <- \"bestelbon\"

Now I want to find the largest common substring that starts at the

11条回答
  •  礼貌的吻别
    2021-02-19 18:49

    flodel <- function(word1, word2) {
       # the length of the shorter word
       n <- min(nchar(word1), nchar(word2))
       # two vectors of characters of the same length n
       c1 <- strsplit(word1, "", fixed = TRUE)[[1]][1:n]
       c2 <- strsplit(word2, "", fixed = TRUE)[[1]][1:n]
       # a vector that is TRUE as long as the characters match
       m <- as.logical(cumprod(c1 == c2))
       # the answer
       paste(c1[m], collapse = "")
    }
    

提交回复
热议问题