0

I have a string for example, abcdepzxtru

I want to reverse only a part of the string and I have the beginning and the ending indices of the substring, say 1 and 5, i.e. I need to reverse abcde part of abcedpzxtru and the output should be edcbapzxtru

I am not sure how to do this in R and googling around is not very helpful.

Morpheus
  • 3,285
  • 4
  • 27
  • 57

3 Answers3

4

Using stringi...

library(stringi)
s <- "abcdepzxtru"

substr(s,1,5) <- stri_reverse(substr(s,1,5))

s
[1] "edcbapzxtru"
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32
2
sapply(strsplit("abcdepzxtru", ""),
       function(x) paste(x[c(5:1, 6:length(x))], collapse = ""))
#[1] "edcbapzxtru"
d.b
  • 32,245
  • 6
  • 36
  • 77
2
str <- "abcedpzxtru"
init <- 1
end <- 4
paste(c(sapply(end:init, (function(i) substr(str, i, i))), 
      substr(str,(end+1),nchar(str))), collapse = "", sep = "")

# [1] "ecbadpzxtru"
Damiano Fantini
  • 1,925
  • 9
  • 11