Programing

문자열에서 문자의 위치 찾기

lottogame 2020. 10. 10. 09:28
반응형

문자열에서 문자의 위치 찾기


문자열에서 문자의 위치를 ​​찾고 싶습니다.

말하다: string = "the2quickbrownfoxeswere2tired"

함수를 반환 4하고 -s 24의 문자 위치를 .2string


당신이 사용할 수있는 gregexpr

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


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

또는 아마도 ( 버전 1.0 기준) 래퍼 인 str_locate_all패키지에서stringrgregexpr 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'))

SHOULD 작업 (문자 벡터 제공 x)


또 다른 간단한 대안이 있습니다.

> which(strsplit(string, "")[[1]]=="2")
[1]  4 24

unlist를 사용하여 출력을 4와 24로 만들 수 있습니다.

unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))
[1]  4 24

str1 (Oracle SQL INSTR과 동일한 순서의 매개 변수)에서 str2의 n 번째 발생 위치를 찾고, 찾을 수없는 경우 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

첫 번째 위치 만 찾으려면 다음 lapply()과 함께 사용하십시오 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()함께 사용하십시오 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

참고 URL : https://stackoverflow.com/questions/14249562/find-the-location-of-a-character-in-string

반응형