Search code examples
rstringtrimstringr

Remove extra spaces from entire sentence


I have below variable

sen <- "I have a    sentence  "

I just want to remove spaces from above sentence (all of spaces, beginning end & middle), I know how to use str_trim(sen), but that only removes beginning & end spaces.I want to get rid of middle as well

Required Output "I have a sentence"


Solution

  • You are in luck because there is exact same function in stringr package str_squish()

    this should do what you want to achieve

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

    Output: "I have a sentence"