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

时间:2015-03-17 21:58:06

标签: r string

考虑字符串:

a <- "this is a string"

现在,grep可用于确认子串的存在:

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

但似乎没有给出位置。

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

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

getLoction(a, "this")
## 1

1 个答案:

答案 0 :(得分:1)

在这里,我偏向于使用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
相关问题