Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the location of a character in string

Tags:

string

regex

r

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 string.

like image 819
ricardo Avatar asked Jan 10 '13 01:01

ricardo


People also ask

How do I find the location of a string in Python?

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.

How do I find a specific character in a string Java?

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.


2 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 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)

like image 181
mnel Avatar answered Oct 18 '22 17:10

mnel


Here's another straightforward alternative.

> which(strsplit(string, "")[[1]]=="2") [1]  4 24 
like image 38
Jilber Urbina Avatar answered Oct 18 '22 16:10

Jilber Urbina