用新字符替换字符串中的所有字符,r中的空白除外



我有一个字符串,例如:str <- c("a string","of words","also some spaces")我想把它们变成strx <- c("x xxxxxx","xx xxxxx","xxxx xxxx xxxxxx")

我只考虑使用str_length()来计算长度,以获得每个字符串的字符数。那我就无计可施了,请帮帮我。如有任何建议,我们将不胜感激。

我们可以匹配非空白字符(\S),并在base R中使用gsub替换为x

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

最新更新