martinctc
8/26/2017 - 9:54 PM

Replace nth occurring value in a string

Replace nth occurring value in a string

str_replace_n <- function(x, pattern, replace, n){
  g <- gregexpr(pattern,x)[[1]][n]
  output <- paste0(substr(x,1,g-1),replace,substr(x,g+1,nchar(x)))
  output
}

str_replace_n("ALLAHABAD","A","U",3)
#[1] "ALLAHUBAD"

str_replace_nth <- function(x, pattern, replacement, n) {
  g <- gregexpr(pattern, x)[[1]][n]
  s <- scan(text = gsub("[()]", "", pattern),
            sep = "|",
            what = "")
  substr(x, g, g) <- replacement[match(substr(x, g, g), s)]
  x
}

str_replace_nth("ALLAHABAD","A","U",2)
#[1] "ALLUHABAD"