Find the location of a character in a string

I would like to find the location of the character in the string.

Say: string = "the2quickbrownfoxeswere2tired"

I want the function to return 4 and 24 - the location of character 2 in string .

+78
string regex r
Jan 10 '13 at 1:44
source share
4 answers

You can use gregexpr

  gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired") [[1]] [1] 4 24 attr(,"match.length") [1] 1 1 attr(,"useBytes") [1] TRUE 

or perhaps str_locate_all from the str_locate_all package, which is the wrapper for gregexpr stringi::stri_locate_all (starting with stringr version 1.0)

 library(stringr) str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired") [[1]] start end [1,] 4 4 [2,] 24 24 

note that you can just use stringi

 library(stringi) stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE) 

Another option in the R base would be something like

 lapply(strsplit(x, ''), function(x) which(x == '2')) 

should work (given the character vector x )

+104
Jan 10 '13 at 1:47
source share

Here is another simple alternative.

 > which(strsplit(string, "")[[1]]=="2") [1] 4 24 
+34
Oct 06 '13 at 23:16
source share

You can only conclude 4 and 24 using the list:

 unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")) [1] 4 24 
+16
Sep 27 '15 at 3:32
source share

find the position of the nth occurrence of str2 in str1 (the same order of parameters as Oracle SQL INSTR), returns 0 if not found

 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 
+2
08 Oct '15 at 2:35
source share



All Articles