92

我想在字符串中找到一个字符的位置。

说:string = "the2quickbrownfoxeswere2tired"

我希望函数返回4-中s24的字符位置。2string

4

6 回答 6

123

您可以使用gregexpr

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


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

或者可能str_locate_all来自stringr作为包装器的包(从1.0 版开始)gregexpr 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 回答
4

在str1中找到str2第n次出现的位置(参数顺序与Oracle SQL INSTR相同),如果没有找到返回0

instr <- function(str1,str2,startpos=1,n=1){
    aa=unlist(strsplit(substring(str1,startpos),str2))
    if(length(aa) < n+1 ) return(0);
    return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2) )
}


instr('xxabcdefabdddfabx','ab')
[1] 3
instr('xxabcdefabdddfabx','ab',1,3)
[1] 15
instr('xxabcdefabdddfabx','xx',2,1)
[1] 0
于 2015-10-08T02:35:59.233 回答
2

要仅查找第一个位置,请使用lapply()with min()

my_string <- c("test1", "test1test1", "test1test1test1")

unlist(lapply(gregexpr(pattern = '1', my_string), min))
#> [1] 5 5 5

# or the readable tidyverse form
my_string %>%
  gregexpr(pattern = '1') %>%
  lapply(min) %>%
  unlist()
#> [1] 5 5 5

要仅查找最后的位置,请使用lapply()with max()

unlist(lapply(gregexpr(pattern = '1', my_string), max))
#> [1]  5 10 15

# or the readable tidyverse form
my_string %>%
  gregexpr(pattern = '1') %>%
  lapply(max) %>%
  unlist()
#> [1]  5 10 15
于 2019-08-12T09:08:31.143 回答
2

你也可以使用grep

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