2012-06-19 32 views
6

我有一串字符串,其中一些是相當長的,就像這樣: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") 

我現在想這些字符串截斷到最大的,比方說,30個字符,但以這樣的方式,在該過程中沒有單詞被分割,理想情況下,如果該字符串被截斷,則將橢圓添加到該字符串的末尾。

回答

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 ..."