92

文字列内の文字の位置を見つけたいです。

言う:string = "the2quickbrownfoxeswere2tired"

関数が返してほしいと思います4-のs の24文字位置。2string

4

6 に答える 6

123

使用できますgregexpr

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


[[1]]
[1]  4 24
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE

またはおそらく(バージョン1.0の時点で)のラッパーであるstr_locate_allパッケージからstringrgregexpr stringi::stri_locate_allstringr

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

[[1]]
     start end
[1,]     4   4
[2,]    24  24

単に使用できることに注意してくださいstringi

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

ベースの別のオプションはR次のようなものです

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

動作するはずです (文字ベクトルを指定x)

于 2013-01-10T01:47:44.947 に答える
43

別の簡単な代替手段を次に示します。

> which(strsplit(string, "")[[1]]=="2")
[1]  4 24
于 2013-10-06T23:16:50.203 に答える
21

unlist を使用して、出力を 4 と 24 にすることができます。

unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))
[1]  4 24
于 2015-09-27T03:32:39.257 に答える
2

grep同様に使用できます:

grep('2', strsplit(string, '')[[1]])
#4 24
于 2020-10-03T18:50:21.733 に答える