从整个句子中删除多余的空格

Remove extra spaces from entire sentence

我有以下变量

sen <- "I have a    sentence  "

我只想从上面的句子中删除空格(所有空格,开头结尾和中间),我知道如何使用 str_trim(sen),但这只会删除开头和结尾 spaces.I 想要也摆脱中间

要求输出"I have a sentence"

你很幸运,因为在 stringr 包中有完全相同的功能 str_squish()

这应该可以达到您想要的效果

library(stringr)
sen <- "I have a    sentence  "
str_squish(sen)
print(sen)

输出:"I have a sentence"

我们可以使用 gsub 将多个 space 替换为一个 space。我们将其包装在 trimws 中以删除出现在字符串开头和结尾的 space。

trimws(gsub("\s+", " ", sen))
#[1] "I have a sentence"