0 votes
1 view
in R Programming by (5.1k points)

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 2s in the string.

1 Answer

0 votes
by (23.2k points)

To find the location of a character in a string, you can use the str_locate_all function from the stringr package.

In your case:

 str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired")

[[1]]

     start end

[1,]     4   4

[2,]    24  24

You can also use the stringi package as follows:

library(stringi)

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

[[1]]

     start end

[1,]     4   4

[2,]    24  24

...