I would like to find the location of a character in a string.
Say: string = "the2quickbrownfoxeswere2tired"
I would like the function to return 4
and 24
-- the character location of the 2
s in string
.
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found then it returns -1.
You can search for a particular letter in a string using the indexOf() method of the String class. This method which returns a position index of a word within the string if found. Otherwise it returns -1.
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 package stringr
which is a wrapper for gregexpr
stringi::stri_locate_all
(as of stringr
version 1.0)
library(stringr) str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired") [[1]] start end [1,] 4 4 [2,] 24 24
note that you could simply use stringi
library(stringi) stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)
Another option in base R
would be something like
lapply(strsplit(x, ''), function(x) which(x == '2'))
should work (given a character vector x
)
Here's another straightforward alternative.
> which(strsplit(string, "")[[1]]=="2") [1] 4 24
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With