我想在字符串中的特定位置插入一个额外的字符(或一个新字符串).例如,我想d
在第四个位置插入abcefg
以获取abcdefg
.
现在我正在使用:
old <- "abcefg"
n <- 4
paste(substr(old, 1, n-1), "d", substr(old, n, nchar(old)), sep = "")
Run Code Online (Sandbox Code Playgroud)
我可以为这个任务编写一个单行的简单函数,但我很好奇是否有一个现有的函数.
Jus*_*tin 58
您可以使用正则表达式和gsub
.
gsub('^([a-z]{3})([a-z]+)$', '\\1d\\2', old)
# [1] "abcdefg"
Run Code Online (Sandbox Code Playgroud)
如果要动态执行此操作,可以使用paste
以下命令创建表达式:
letter <- 'd'
lhs <- paste0('^([a-z]{', n-1, '})([a-z]+)$')
rhs <- paste0('\\1', letter, '\\2')
gsub(lhs, rhs, old)
# [1] "abcdefg"
Run Code Online (Sandbox Code Playgroud)
根据DWin的评论,您可能希望这更加通用.
gsub('^(.{3})(.*)$', '\\1d\\2', old)
Run Code Online (Sandbox Code Playgroud)
这样任何三个字符都匹配而不仅仅是小写.DWin还建议使用sub
而不是gsub
.这样您就不必担心这一点^
,因为sub
只会匹配第一个实例.但是我喜欢在正则表达式中明确表达,而只是在我理解它们时转向更一般的表达式,并且需要更多的通用性.
正如Greg Snow所说,你可以使用另一种形式的正则表达式来查看匹配:
sub( '(?<=.{3})', 'd', old, perl=TRUE )
Run Code Online (Sandbox Code Playgroud)
并且还可以gsub
使用sprintf
而不是paste0
:
lhs <- sprintf('^([a-z]{%d})([a-z]+)$', n-1)
Run Code Online (Sandbox Code Playgroud)
或者他的sub
正则表达式:
lhs <- sprintf('(?<=.{%d})',n-1)
Run Code Online (Sandbox Code Playgroud)
bar*_*nus 17
stringi
包再次救援!现有的解决方案中最简单,最优雅的解决方案
stri_sub
函数允许您提取字符串的一部分并替换它的部分,如下所示:
x <- "abcde"
stri_sub(x, 1, 3) # from first to third character
# [1] "abc"
stri_sub(x, 1, 3) <- 1 # substitute from first to third character
x
# [1] "1de"
Run Code Online (Sandbox Code Playgroud)
但是如果你这样做:
x <- "abcde"
stri_sub(x, 3, 2) # from 3 to 2 so... zero ?
# [1] ""
stri_sub(x, 3, 2) <- 1 # substitute from 3 to 2 ... hmm
x
# [1] "ab1cde"
Run Code Online (Sandbox Code Playgroud)
然后没有删除任何字符但插入新的字符.那不是很酷吗?:)
@贾斯汀的答案是其实我的方法,因为它的灵活性这个问题的方法,但是这也可能是一个有趣的方法.
您可以将字符串视为"固定宽度格式"并指定要插入字符的位置:
paste(read.fwf(textConnection(old),
c(4, nchar(old)), as.is = TRUE),
collapse = "d")
Run Code Online (Sandbox Code Playgroud)
特别好的是使用时的输出sapply
,因为你可以看到原始字符串作为"名称".
newold <- c("some", "random", "words", "strung", "together")
sapply(newold, function(x) paste(read.fwf(textConnection(x),
c(4, nchar(x)), as.is = TRUE),
collapse = "-WEE-"))
# some random words strung together
# "some-WEE-NA" "rand-WEE-om" "word-WEE-s" "stru-WEE-ng" "toge-WEE-ther"
Run Code Online (Sandbox Code Playgroud)