I am lookin for an efficient way to reduce a large sentence to a specific length and ending on an entire word.
For example reduce each sentence to max 24 characters and end on whole word.
fruits <- c(
"apples and oranges and pears and bananas",
"pineapples and mangos and guavas"
)
to
"apples and oranges and", "pineapples and mangos"
Take an extra character, then remove everything after (and including) the last space.
fruits <- c(
"apples and oranges and pears and bananas",
"pineapples and mangos and guavas"
)
n <- 24
sub(
" [^ ]*$",
"",
substr(fruits, 1, n + 1)
)
#> [1] "apples and oranges and" "pineapples and mangos"
Another option with sub
> sub("(.{1,24}(?<=\\S)(?= )).*", "\\1", fruits, perl = TRUE)
[1] "apples and oranges and" "pineapples and mangos"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With