मैं एक स्ट्रिंग में एक चरित्र का स्थान ढूंढना चाहूंगा।
कहते हैं: string = "the2quickbrownfoxeswere2tired"
मैं चाहूंगा कि समारोह में वापसी हो 4और 24- एस के चरित्र स्थान 2में string।
मैं एक स्ट्रिंग में एक चरित्र का स्थान ढूंढना चाहूंगा।
कहते हैं: string = "the2quickbrownfoxeswere2tired"
मैं चाहूंगा कि समारोह में वापसी हो 4और 24- एस के चरित्र स्थान 2में string।
जवाबों:
आप उपयोग कर सकते हैं 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)gregexprstringi::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)
regexprबजाय उपयोग करें gregexpr। या unlistआउटपुट पर उपयोग करें जैसा कि नीचे एक अन्य उत्तर में दिया गया है।
यहाँ एक और सीधा विकल्प है।
> which(strsplit(string, "")[[1]]=="2")
[1] 4 24
[[1]]करता है?
आप अनलिस्ट का उपयोग करके केवल 4 और 24 आउटपुट कर सकते हैं:
unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))
[1] 4 24
str1 में str2 की nth घटना की स्थिति का पता लगाएं (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
केवल पहले स्थानों को खोजने के लिए , इसके 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
.indexOf()या कुछ नहीं है?