如何从字符串中删除所有空格? [英] How to remove all whitespace from a string?

查看:695
本文介绍了如何从字符串中删除所有空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此xx yy 11 22 33会变成xxyy112233。我怎样才能做到这一点?

解决方案

一般来说,我们需要一个矢量化的解决方案,所以这里有一个更好的测试示例: / p>

 空格< - \t\\\
\r\v\f#space,tab,newline ,
#回车符,垂直制表符,换行符
x< - c(
xy,#位于
之前,之后和之间的空格)\\\← \\\→ ,#包含unicode字符
paste0(#变量空格
空格,
x,
空格,
y,
空格,$
##[1]xy
## [2]←→b $ b collapse =
),
NA#缺少

## [3]\t\\\
\r\v\fx\t\\\
\r\v\fy\t\\\
\r\\ \\ v \ f
## [4] NA






基本的R方法: gsub



gsub 替换字符串的所有实例( fixed = TRUE )或正则表达式( fixed = FALSE ,默认值)与另一个字符串。要删除所有空格,请使用:

  gsub(,,x,fixed = TRUE)
# #[1]xy←→
## [3]\t\\\
\r\v\fx\t\\\
\r\v\ f'\\'t \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ,在这种情况下, fixed = TRUE 不是必需的,但由于匹配固定字符串比匹配正则表达式快,所以性能稍好。



如果您想删除所有类型的空白,请使用:

  gsub([[:space :]],,x)#注意双方括号
## [1]xy←→xyNA

gsub(\\\ \\,,x)#相同;注意双反斜杠

library(regex)
gsub(space(),,x)#same

[:space:] 是一个与特定R空间字符匹配的正则表达式组。 \s 是一种独立于语言的正则表达式,可以做同样的事情。




stringr 方法: str_replace_all str_trim



stringr 提供了更多可读的基本R函数包装(尽管截至2014年12月,开发版本具有建立在 stringi 之上的分支,如下所述)。上述命令的等价物使用[ str_replace_all] [3] ,为:

  b $ b $ str_replace_all(x,fixed(),)
str_replace_all(x,space(),)

stringr 也有一个 str_trim 函数,它只删除前导和尾随空格。

  str_trim(x)
## [1]xy←→x \ t\\\
\ r \v\fyNA
str_trim(x,left)
## [1]xy←→
## [3]x \ t \\\\\\\\\\\\\\\\\\\\\\\\\\\\' ]xy←→
## [3]\t\\\
\r\v\fx\t\\\
\r\v\fy不适用






s tringi 方法: stri_replace_all_charclass stri_trim



stringi 建立在独立于平台的 ICU库,并有一套广泛的字符串操作功能。上面的等价物是:

  library(stringi)
stri_replace_all_fixed(x,,)
stri_replace_all_charclass(x,\\p {WHITE_SPACE },)

这里 \\p {WHITE_SPACE} 是一个被认为是空格的一组Unicode代码点的替代语法,相当于[[:space:]]\\ s space()。对于更复杂的正则表达式替换,还有 stri_replace_all_regex



stringi 也有修剪功能

  stri_trim(x)
stri_trim_both(x)#same
stri_trim(x,left)
stri_trim_left x)#same
stri_trim(x,right)
stri_trim_right(x)#same


So " xx yy 11 22 33 " will become "xxyy112233". How can I achieve this?

解决方案

In general, we want a solution that is vectorised, so here's a better test example:

whitespace <- " \t\n\r\v\f" # space, tab, newline, 
                            # carriage return, vertical tab, form feed
x <- c(
  " x y ",           # spaces before, after and in between
  " \u2190 \u2192 ", # contains unicode chars
  paste0(            # varied whitespace     
    whitespace, 
    "x", 
    whitespace, 
    "y", 
    whitespace, 
    collapse = ""
  ),   
  NA                 # missing
)
## [1] " x y "                           
## [2] " ← → "                           
## [3] " \t\n\r\v\fx \t\n\r\v\fy \t\n\r\v\f"
## [4] NA


The base R approach: gsub

gsub replaces all instances of a string (fixed = TRUE) or regular expression (fixed = FALSE, the default) with another string. To remove all spaces, use:

gsub(" ", "", x, fixed = TRUE)
## [1] "xy"                            "←→"             
## [3] "\t\n\r\v\fx\t\n\r\v\fy\t\n\r\v\f" NA 

As DWin noted, in this case fixed = TRUE isn't necessary but provides slightly better performance since matching a fixed string is faster than matching a regular expression.

If you want to remove all types of whitespace, use:

gsub("[[:space:]]", "", x) # note the double square brackets
## [1] "xy" "←→" "xy" NA 

gsub("\\s", "", x)         # same; note the double backslash

library(regex)
gsub(space(), "", x)       # same

"[:space:]" is an R-specific regular expression group matching all space characters. \s is a language-independent regular-expression that does the same thing.


The stringr approach: str_replace_all and str_trim

stringr provides more human-readable wrappers around the base R functions (though as of Dec 2014, the development version has a branch built on top of stringi, mentioned below). The equivalents of the above commands, using [str_replace_all][3], are:

library(stringr)
str_replace_all(x, fixed(" "), "")
str_replace_all(x, space(), "")

stringr also has a str_trim function which removes only leading and trailing whitespace.

str_trim(x) 
## [1] "x y"          "← →"          "x \t\n\r\v\fy" NA    
str_trim(x, "left")    
## [1] "x y "                   "← → "    
## [3] "x \t\n\r\v\fy \t\n\r\v\f" NA     
str_trim(x, "right")    
## [1] " x y"                   " ← →"    
## [3] " \t\n\r\v\fx \t\n\r\v\fy" NA      


The stringi approach: stri_replace_all_charclass and stri_trim

stringi is built upon the platform-independent ICU library, and has an extensive set of string manipulation functions. The equivalents of the above are:

library(stringi)
stri_replace_all_fixed(x, " ", "")
stri_replace_all_charclass(x, "\\p{WHITE_SPACE}", "")

Here "\\p{WHITE_SPACE}" is an alternate syntax for the set of Unicode code points considered to be whitespace, equivalent to "[[:space:]]", "\\s" and space(). For more complex regular expression replacements, there is also stri_replace_all_regex.

stringi also has trim functions.

stri_trim(x)
stri_trim_both(x)    # same
stri_trim(x, "left")
stri_trim_left(x)    # same
stri_trim(x, "right")  
stri_trim_right(x)   # same

这篇关于如何从字符串中删除所有空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆