Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a character at a specific location in a string

Tags:

string

r

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.

Now I am using:

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.

like image 862
JACKY Li Avatar asked Dec 13 '12 15:12

JACKY Li


People also ask

How do you insert a character in a string at a certain position?

One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.

How do I find a character in a certain position in a string Java?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you add a string to a specific position in Python?

If you need to insert a given char at multiple locations, always consider creating a list of substrings and then use . join() instead of + for string concatenation. This is because, since Python str are mutable, + string concatenation always adds an aditional overhead.


1 Answers

You can do this with regular expressions and gsub.

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

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" 

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

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

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.


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

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

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

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

or for his sub regular expression:

lhs <- sprintf('(?<=.{%d})',n-1) 
like image 188
Justin Avatar answered Sep 25 '22 10:09

Justin