在字符串的特定位置插入一个字符 [英] Insert a character at a specific location in a string

查看:74
本文介绍了在字符串的特定位置插入一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字符串的特定位置插入一个额外的字符(或新字符串).比如我想在abcefg的第四个位置插入d得到abcdefg.

I would like to insert an extra character (or a new string) at a specific location in a string. For example, I want to insert d at the fourth location in abcefg to get abcdefg.

现在我正在使用:

old <- "abcefg"
n <- 4
paste(substr(old, 1, n-1), "d", substr(old, n, nchar(old)), sep = "")

我可以为此任务编写一个简单的单行函数,但我很好奇是否有用于该任务的现有函数.

I could write a one-line simple function for this task, but I am just curious if there is an existing function for that.

推荐答案

您可以使用正则表达式和 gsub 来做到这一点.

You can do this with regular expressions and gsub.

gsub('^([a-z]{3})([a-z]+)$', '\\1d\\2', old)
# [1] "abcdefg"

如果您想动态执行此操作,可以使用 paste 创建表达式:

If you want to do this dynamically, you can create the expressions using paste:

letter <- 'd'
lhs <- paste0('^([a-z]{', n-1, '})([a-z]+)$')
rhs <- paste0('\\1', letter, '\\2')
gsub(lhs, rhs, old)
# [1] "abcdefg"

<小时>

根据 DWin 的评论,您可能希望这更通用.


as per DWin's comment,you may want this to be more general.

gsub('^(.{3})(.*)$', '\\1d\\2', old)

这样可以匹配任意三个字符,而不仅仅是小写.DWin 还建议使用 sub 而不是 gsub.这样你就不必担心 ^ 因为 sub 只会匹配第一个实例.但我喜欢在正则表达式中明确表达,并且只在我理解它们并发现需要更多通用性时才转向更通用的.

This way any three characters will match rather than only lower case. DWin also suggests using sub instead of gsub. This way you don't have to worry about the ^ as much since sub will only match the first instance. But I like to be explicit in regular expressions and only move to more general ones as I understand them and find a need for more generality.

正如 Greg Snow 所指出的,您可以使用另一种形式的正则表达式来查看匹配项:

as Greg Snow noted, you can use another form of regular expression that looks behind matches:

sub( '(?<=.{3})', 'd', old, perl=TRUE )

并且还可以使用 sprintf 而不是 paste0 在上面构建我的动态 gsub:

and could also build my dynamic gsub above using sprintf rather than paste0:

lhs <- sprintf('^([a-z]{%d})([a-z]+)$', n-1) 

或者对于他的 sub 正则表达式:

or for his sub regular expression:

lhs <- sprintf('(?<=.{%d})',n-1)

这篇关于在字符串的特定位置插入一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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