R语言 用&-符号替换字符中的最后一个逗号

R语言 用&-符号替换字符中的最后一个逗号

R语言中的字符串是一个字符序列,它包含数字、字符和特殊符号。这些字符可以在字符串中被修改、插入和删除。R提供了大量的函数和外部包来进行字符串的修改。在这篇文章中,我们将看到如何在R编程语言中用&-符号替换最后一个逗号的字符。

方法1:使用sub()方法

R语言中的sub()方法是用来用一个新的字符串替换字符串的指定部分。sub()方法的使用也与正则表达式兼容,它的语法如下:

语法: sub(search, replacement, str)

参数:

  • search – 要在字符串中查找的搜索词
  • replacement – 用新的字符串来替换搜索词
  • str – 要进行替换的字符串
# creating a dummy string 
str <- "Hi Neena, Reena, Teena"
print("Input String")
print(str)
  
# replace the last comma with &
out_str <- sub(",([^,]*)$", " &\\1", str) 
print("Output String")
print(out_str)

输出

[1] "Input String"
[1] "Hi Neena, Reena, Teena"
[1] "Output String"
[1] "Hi Neena, Reena & Teena"

方法2:使用stringr包

R中的stringr包用于进行字符串操作。它可以通过以下命令下载并安装到工作空间。

install.packages("stringr")

这个包中包含了一系列的方法,可以用来进行字符串的修改。最初,str_locate_all()方法被应用于字符串,以定位逗号字符串的所有出现。

# installing the reqd libraries
library("stringr")
  
# creating a dummy string 
str <- "Hi A, B, C"
print("Input String")
print(str)
  
# locating the places of comma occurrence
loc_comma <- str_locate_all(str, ",")[[1]]  
  
# calculating the number of positions 
# in comma array
comma_ele <- nrow(loc_comma)
  
# fetching the last comma position
last_loc_comma <- loc_comma[ comma_ele , ] 
  
# replace the last comma with & symbol 
str_sub(str, last_loc_comma[1], 
        last_loc_comma[2]) <- " &"  
print("Output String")
print(str)

输出

[1] "Input String"
[1] "Hi A, B, C"
[1] "Output String"
[1] "Hi A, B & C"

方法3:使用stringi包

R中的stringi包用于进行字符串操作。它可以通过以下命令下载并安装到工作空间。

install.packages("stringi")

stri_replace_last()方法直接用于替换字符串中最后出现的指定模式。该方法的语法如下。

语法: stri_replace_last(str, fixed, replacement)

参数 :

  • str – 要替换的字符的字符串
  • fixed – 要寻找的固定模式
  • replacement – 要用固定模式替换的字符串

这里,在最后一次出现的字符串”,”

# installing the reqd libraries
library("stringi")
  
# creating a dummy string 
str <- "Hi A, B, C"
print("Input String")
print(str)
  
# replacing the last comma with
# &
out_str <- stri_replace_last(
  str, fixed = ",", " &")  
  
# printing the output string
print("Output String")
print(out_str)

输出

[1] "Input String"
[1] "Hi A, B, C"
[1] "Output String"
[1] "Hi A, B & C"

方法4:使用内置的字符串方法

R包含了一系列内置的方法来进行数据修正和访问。最初,使用strsplit()方法将字符串分割成不同的片段,该方法用于将作为参数给出的字符向量的部分分割到strsplit()方法中。然后,它用指定的子串将其分割成不同的子串。该方法的语法如下:

# creating a dummy string 
str <- "Hi A, B, C"
print("Input String")
print(str)
  
# split the string characters
splt_str <- strsplit(str, "")
  
# divide the string into individual
# strings
str_unlist <- unlist(splt_str)   
  
# used to fetch the position of the 
# comma 
str_comma <- grep(",", str_unlist)
  
# replace the last position of
# the comma array with a & symbol 
str_unlist[tail(str_comma, 1)] <- " &" 
  
# remerge the string using empty spaces
out_str <- paste0(str_unlist, collapse = "")  
print("Output String")
print(out_str)

输出

[1] "Input String"
[1] "Hi A, B, C"
[1] "Output String"
[1] "Hi A, B & C"

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程