2017-08-29 38 views
0

我的字符串,例如串逆转,abcdepzxtru代替R中

我想要扭转只有字符串的一部分,我已经开始和字符串的结束指数,比如说1和5 ,即我需要反转abcde部分abcedpzxtru和输出应该是edcbapzxtru

我不知道如何做到这一点在R和谷歌搜索并不是很有帮助。

+1

按照复制链接扭转一个字符串,然后你到刚刚拍摄使用索引的子。 –

回答

4

使用stringi ...

library(stringi) 
s <- "abcdepzxtru" 

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

s 
[1] "edcbapzxtru" 
2
sapply(strsplit("abcdepzxtru", ""), 
     function(x) paste(x[c(5:1, 6:length(x))], collapse = "")) 
#[1] "edcbapzxtru" 
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"