我试图创建一个for循环,当它在任何给定字符串中找到第二个“ e”或“ E”时停止。到目前为止,我已经提出了这段代码,但是输出错误。任何想法都会有所帮助。
mystring <- "R fever"
index <- 1
ecount <- 0
result <- mystring
while(ecount<2 && index <= nchar(mystring)){
substr(mystring, 1, index) -> result
if(result == "e" || result == "E") {ecount = ecount + 1}
if(ecount == 2) {
sustr(result, 1, index-1)
}
index <- index +1
cat(result)
}
答案 0 :(得分:1)
如果您真的想坚持使用该循环:
mystring <- "R fever"
index <- 1
ecount <- 0
result <- mystring
while(ecount<2 && index <= nchar(mystring)){
substr(mystring, index, index) -> result
if(result == "e" || result == "E") {ecount = ecount + 1}
if(ecount == 2) {
substr(result, 1, index-1)
}
index <- index +1
cat(result)
}
# R feve
您在substr(mystring, 1, index)
中只有一个问题,应该是substr(mystring, index, index)
。
否则,有更简单的选择。例如:
strsplit(sub('(^[^e]*e[^e]*)e(.*)$', '\\1e_\\2', mystring), "_", mystring)[[1]][1]
# [1] "R feve"