R: find largest common substring starting at the beginning

后端 未结 11 2558
星月不相逢
星月不相逢 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:52

    This seems to work

    longestprefix<-function(a,b) {
        n <- pmin(nchar(a), nchar(b))
        mapply(function(x, y, n) {
            rr<-rle(x[1:n]==y[1:n])
            if(rr$values[1]) {
                paste(x[1:rr$lengths[1]], collapse="")
            } else {
                ""
            }
        }, strsplit(a, ""), strsplit(b,""), n)
    }
    
    
    
    longestprefix("bestelling", "bestelbon")
    # [1] "bestel"
    longestprefix("bestelling", "stel")
    # [1] ""
    

提交回复
热议问题