Eu gostaria de encontrar a localização de um caractere em uma string.
Diga: string = "the2quickbrownfoxeswere2tired"
Eu gostaria que a function retornasse 4
e 24
– a localização do caractere dos 2
s na string
.
Você pode usar gregexpr
gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired") [[1]] [1] 4 24 attr(,"match.length") [1] 1 1 attr(,"useBytes") [1] TRUE
ou talvez str_locate_all
do pacote stringr
que é um wrapper para gregexpr
stringi::stri_locate_all
(a partir da versão 1.0 do stringr
)
library(stringr) str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired") [[1]] start end [1,] 4 4 [2,] 24 24
note que você poderia simplesmente usar stringi
library(stringi) stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)
Outra opção na base R
seria algo como
lapply(strsplit(x, ''), function(x) which(x == '2'))
deve funcionar (dado um vetor de caracteres x
)
Aqui está outra alternativa simples.
> which(strsplit(string, "")[[1]]=="2") [1] 4 24
Você pode fazer a saída apenas 4 e 24 usando unlist:
unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")) [1] 4 24
encontre a posição da enésima ocorrência de str2 em str1 (mesma ordem de parâmetros que o Oracle SQL INSTR), retorna 0 se não for encontrado
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