查找字符在字符串中的位置 [英] Find the location of a character in string
本文介绍了查找字符在字符串中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找到一个字符在字符串中的位置.
I would like to find the location of a character in a string.
说:string = "the2quickbrownfoxeswere2tired"
我希望函数返回 4
和 24
-- 2
在 string中的字符位置代码>.
I would like the function to return 4
and 24
-- the character location of the 2
s in string
.
推荐答案
您可以使用 gregexpr
gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")
[[1]]
[1] 4 24
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE
或者 str_locate_all
来自包 stringr
,它是 gregexpr
stringi::stri_locate_all 的包装器
(从 stringr
1.0 版开始)
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
请注意,您可以简单地使用 stringi
note that you could simply use stringi
library(stringi)
stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)
基础 R
中的另一个选项类似于
Another option in base R
would be something like
lapply(strsplit(x, ''), function(x) which(x == '2'))
应该可以工作(给定一个字符向量 x
)
should work (given a character vector x
)
这篇关于查找字符在字符串中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文