6

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

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 个字符,但在此过程中不会拆分任何单词,并且理想情况下,如果字符串被截断,则将省略号添加到字符串的末尾.

4

2 回答 2

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 ..."
于 2012-06-19T13:41:09.937 回答
0

我建议你看看这个abbreviate功能。它缩写字符串,并允许一些控制。看:

http://stat.ethz.ch/R-manual/R-devel/library/base/html/abbreviate.html

对于手册页。

于 2012-06-19T13:43:15.710 回答