R: Truncate string without splitting words
r, string
Solution
Here's an R-based solution:
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 ..."
Problem
I have bunch of strings, some of which are fairly long, like so: ``` movie.titles <- c("Il divo: La spettacolare vita di Giulio Andreotti","Defiance","Coco Before Chanel","Happy-Go-Lucky","Up","The Imaginarium of Doctor Parnassus") ``` I would now like to truncate these strings to a maximum of, say, 30 characters, but in such a way that no words are split up in the process and ideally such that if the string is truncated ellipses are added to the end of the string.