R: find largest common substring starting at the beginning

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

    Here's another function that seems to work.

    foo <- function(word1, word2) {
        s1 <- substring(word1, 1, 1:nchar(word1))
        s2 <- substring(word2, 1, 1:nchar(word2))
        if(length(w <- which(s1 %in% s2))) s2[max(w)] else character(1)
    }
    
    foo("bestelling", "bestelbon")
    # [1] "bestel"
    foo("bestelling", "stel")
    # [1] ""
    foo("bestelbon", "bestieboop")
    # [1] "best"
    foo("stel", "steal")
    # [1] "ste"
    

提交回复
热议问题