获取给定字符串中的子字符串位置

问题描述 投票:0回答:1

考虑字符串:

a <- "this is a string"

现在,

grep
可以用来确认子串是否存在:

grep("t",a)
grep("this",a)

但是好像没有给出位置。

是否有一个函数可以给我任何子字符串的位置?

getLoction(a, "t")
## 1 12

getLoction(a, "this")
## 1
r string
1个回答
2
投票

给你,我偏爱 stringr 包:

library(stringr)
a <- "this is a string"
str_locate(a,"t")
str_locate(a,"this")
str_locate_all(a,"t")

和输出:

> str_locate(a,"t")
     start end
[1,]     1   1
> str_locate(a,"this")
     start end
[1,]     1   4
> str_locate_all(a,"t")
[[1]]
     start end
[1,]     1   1
[2,]    12  12
© www.soinside.com 2019 - 2024. All rights reserved.