文字列内の文字の位置を見つけたいです。
言う:string = "the2quickbrownfoxeswere2tired"
関数が返してほしいと思います4
-のs の24
文字位置。2
string
使用できますgregexpr
gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")
[[1]]
[1] 4 24
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE
またはおそらく(バージョン1.0の時点で)のラッパーであるstr_locate_all
パッケージからstringr
gregexpr
stringi::stri_locate_all
stringr
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
)
別の簡単な代替手段を次に示します。
> which(strsplit(string, "")[[1]]=="2")
[1] 4 24
unlist を使用して、出力を 4 と 24 にすることができます。
unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))
[1] 4 24
grep
同様に使用できます:
grep('2', strsplit(string, '')[[1]])
#4 24