replace all characters in a string with a new character, except blank in R

29 Views Asked by At

I have a string, for example: str <- c("a string","of words","also some spaces") and I'd like to turn them into strx <- c("x xxxxxx","xx xxxxx","xxxx xxxx xxxxxx")

I only have thoughts on count the length using str_length() to get the number of characters of each string. Then I'm out of ideas, please help. Any suggestions will be appreciated.

1

There are 1 best solutions below

0
akrun On

We can match a non-white space character (\\S) and replace with x using gsub in base R

gsub("\\S", "x", str)
#[1] "x xxxxxx"         "xx xxxxx"         "xxxx xxxx xxxxxx"