我有一堆字符串,其中有些相当长,如下所示:
movie.titles <- c("Il divo: La spettacolare vita di Giulio Andreotti","Defiance","Coco Before Chanel","Happy-Go-Lucky","Up","The Imaginarium of Doctor Parnassus")
我现在想将这些字符串截断为最多30个字符,但是这样一来,在处理过程中不会拆分任何单词,理想情况下,如果字符串被截断,则将省略号添加到字符串的末尾。
最佳答案
这是一个基于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 ..."
关于string - R:截断字符串而不拆分单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11101073/