R语言 删除字符串中的所有空白

R语言 删除字符串中的所有空白

在这篇文章中,我们将看到如何在R编程语言中去除字符串的所有空白。

我们可以通过以下方式来实现

  • 使用gsub()函数。
  • 使用str_replace_all()函数。

方法1:使用gsub()函数

gsub()函数是用来去除给定字符串中的空格的。

语法: gsub(” “, “”, input_string)

其中

  1. 第一个参数取空格,以检查字符串是否有空格
  2. 如果字符串中有空格,第二个参数将被替换为 “No space”。
  3. 第三个参数是输入字符串。

例子: R程序使用gsub()函数去除字符串中的空白。

# consider the string
data = "Hello Geek welocme    to Geeksforgeeks"
print("Original String:")
print(data)
  
print("After remove white space:")
  
# remove white spaces
print(gsub(" ","",data))
R

输出

[1] "Original String:"
[1] "Hello Geek welocme    to Geeksforgeeks"
[1] "After remove white space:"
[1] "HelloGeekwelocmetoGeeksforgeeks"
R

方法2:使用str_replace_all()函数

该函数用于将空白处替换为空,它类似于gsub()函数。它在 stringr 软件包中可用。要安装这个模块,请在终端输入以下命令。

install.packages("stringr")
R

这里我们使用str_replace_all()函数来删除字符串中的空白部分。

语法: str_replace_all(input_string,” “, “” )

其中

  1. 第一个参数是输入的字符串
  2. 第二个参数在字符串中有空格的情况下用 “No space “代替
  3. 第三个参数是检查字符串是否有空格

例子: R程序去除字符串中的白色空格

# consider the string
string="Hello Geek welocme    to Geeksforgeeks"
print("Original String:")
print(string)
  
print("After remove white space:")
  
# remove white spaces
print(str_replace_all(string," ",""))
R

输出

[1] "Original String:"
[1] "Hello Geek welocme    to Geeksforgeeks"
[1] "After remove white space:"
[1] "HelloGeekwelocmetoGeeksforgeeks"
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册