且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用字符向量中的单词之间删除多余的空格?

更新时间:2022-12-28 15:11:35

gsub 是你的朋友:

test <- "Hi,  this is a   good  time to   start working   together."
gsub("\\s+"," ",test)
#[1] "Hi, this is a good time to start working together."

\\s+ 将匹配任何空格字符(空格、制表符等)或空格字符的重复,并将其替换为单个空格 " ".

\\s+ will match any space character (space, tab etc), or repeats of space characters, and will replace it with a single space " ".