在string中find字符的位置
我想找一个string中的一个字符的位置。
说: string = "the2quickbrownfoxeswere2tired" 
 我想函数返回4和24 – string中的2秒的字符位置。 
 你可以使用gregexpr 
  gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired") [[1]] [1] 4 24 attr(,"match.length") [1] 1 1 attr(,"useBytes") [1] TRUE 
 或者可能是str_locate_all ,它是封装的stringr ,它是stringr的封装器stringi::stri_locate_all ( stringr version 1.0) 
 library(stringr) str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired") [[1]] start end [1,] 4 4 [2,] 24 24 
 注意你可以简单地使用stringi 
 library(stringi) stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE) 
 基地R另一个select是类似的 
 lapply(strsplit(x, ''), function(x) which(x == '2')) 
 应该工作(给定一个字符向量x ) 
这是另一个直截了当的select。
 > which(strsplit(string, "")[[1]]=="2") [1] 4 24 
您可以使用unlist使输出仅为4和24:
 unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")) [1] 4 24 
在str1中查找str2中第n个出现的位置(与Oracle SQL INSTR相同的参数顺序),如果未find,则返回0
 instr <- function(str1,str2,startpos=1,n=1){ aa=unlist(strsplit(substring(str1,startpos),str2)) if(length(aa) < n+1 ) return(0); return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2) ) } instr('xxabcdefabdddfabx','ab') [1] 3 instr('xxabcdefabdddfabx','ab',1,3) [1] 15 instr('xxabcdefabdddfabx','xx',2,1) [1] 0