R:截断字符串而不分割单词

Roy*_*lTS 6 string r

我有一堆字符串,其中一些相当长,如下:

movie.titles <- c("Il divo: La spettacolare vita di Giulio Andreotti","Defiance","Coco Before Chanel","Happy-Go-Lucky","Up","The Imaginarium of Doctor Parnassus")
Run Code Online (Sandbox Code Playgroud)

我现在想要将这些字符串截断为最多30个字符,但是这样的方式是在过程中不会分割任何单词,理想情况下如果字符串被截断,则将字符串添加到字符串的末尾.

Jos*_*ien 4

这是一个基于 R 的解决方案:

trimTitles <- function(titles) {
    len <- nchar(titles)
    cuts <- sapply(gregexpr(" ", titles), function(X) {
            max(X[X<27])})
    titles[len>=27] <- paste0(substr(titles[len>=27], 0, cuts[len>=27]), "...")
    titles
}
trimTitles(movie.titles)
# [1] "Il divo: La spettacolare ..."  "Defiance"                     
# [3] "Coco Before Chanel"            "Happy-Go-Lucky"               
# [5] "Up"                            "The Imaginarium of Doctor ..."
Run Code Online (Sandbox Code Playgroud)