R: find largest common substring starting at the beginning

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

    As much as I generally avoid a for loop in R - given you're starting at the beginning and continuing until you find the solution it seemed an easy approach.

    It's a bit more intuitive than some of the other examples I think

    lcsB <- function(string1, string2) {
        x <- ''
        for (i in 1:nchar(string1)){
            if (substr(string1[1],1,i) == substr(string2[1],1,i)) {
                x <- substr(string1[1],1,i)
            }
            else
                return(x)
            }
        return(x)
    }
    
    lcsB("bestelling", "bestelbon")
    lcsB("bestelling", "stel")
    

提交回复
热议问题