4

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"

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66

2 Answers2

4

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"

3

We could use gsub to replace more than one space with one space. We wrap it in trimws to remove spaces present at the start and end of the string.

trimws(gsub("\\s+", " ", sen))
#[1] "I have a sentence"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213