Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k 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

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...