# 如何将string拆分成给定长度的子string？

`"aabbccccdd"`

`"aa" "bb" "cc" "cc" "dd"`

` `substring("aabbccccdd", seq(1, 9, 2), seq(2, 10, 2)) #[1] "aa" "bb" "cc" "cc" "dd"` `

` `text <- "aabbccccdd" substring(text, seq(1, nchar(text)-1, 2), seq(2, nchar(text), 2)) #[1] "aa" "bb" "cc" "cc" "dd"` `

` `sst <- strsplit(text, "")[[1]] out <- paste0(sst[c(TRUE, FALSE)], sst[c(FALSE, TRUE)])` `

` `text <- paste(rep(paste0(letters, letters), 1000), collapse="") g1 <- function(text) { substring(text, seq(1, nchar(text)-1, 2), seq(2, nchar(text), 2)) } g2 <- function(text) { sst <- strsplit(text, "")[[1]] paste0(sst[c(TRUE, FALSE)], sst[c(FALSE, TRUE)]) } identical(g1(text), g2(text)) #[1] TRUE library(rbenchmark) benchmark(g1=g1(text), g2=g2(text)) # test replications elapsed relative user.self sys.self user.child sys.child #1 g1 100 95.451 79.87531 95.438 0 0 0 #2 g2 100 1.195 1.00000 1.196 0 0 0` `
` `string <- "aabbccccdd" # total length of string num.chars <- nchar(string) # the indices where each substr will start starts <- seq(1,num.chars, by=2) # chop it up sapply(starts, function(ii) { substr(string, ii, ii+1) })` `

` `[1] "aa" "bb" "cc" "cc" "dd"` `

` `s <- "aabbccccdd"` `
1. `gregexpr``regmatches`

` `regmatches(s, gregexpr(".{2}", s))[[1]] # [1] "aa" "bb" "cc" "cc" "dd"` `
2. `strsplit`

` `strsplit(s, "(?<=.{2})", perl = TRUE)[[1]] # [1] "aa" "bb" "cc" "cc" "dd"` `

` `s2 <- function(x) { m <- matrix(strsplit(x, '')[[1]], nrow=2) apply(m, 2, paste, collapse='') } s2('aabbccddeeff') ## [1] "aa" "bb" "cc" "dd" "ee" "ff"` `

` `s2('abc') ## [1] "ab" "ca" ## Warning message: ## In matrix(strsplit(x, "")[[1]], nrow = 2) : ## data length [3] is not a sub-multiple or multiple of the number of rows [2]` `

` `g1('abc') ## [1] "ab" g2('abc') ## [1] "ab" "cb"` `

` `s <- function(x, n) { sst <- strsplit(x, '')[[1]] m <- matrix('', nrow=n, ncol=(length(sst)+n-1)%/%n) m[seq_along(sst)] <- sst apply(m, 2, paste, collapse='') } s('hello world', 2) ## [1] "he" "ll" "o " "wo" "rl" "d" s('hello world', 3) ## [1] "hel" "lo " "wor" "ld"` `

（它确实比`g2`慢，但比`g1`快7倍）

` `sequenceString <- "ATGAATAAAG" J=3#maximum sequence length in file sequenceSmallVecStart <- substring(sequenceString, seq(1, nchar(sequenceString)-J+1, J), seq(J,nchar(sequenceString), J)) sequenceSmallVecEnd <- substring(sequenceString, max(seq(J, nchar(sequenceString), J))+1) sequenceSmallVec <- c(sequenceSmallVecStart,sequenceSmallVecEnd) cat(sequenceSmallVec,sep = "\n")` `