我有一个问题,即如何替换特定位置的字符。例如:
str <- c("abcdccc","hijklccc","abcuioccc")
#I want to replace character "c" which is in position 3 to "X" how can I do that?
#I know the function gsub and substr, but the only idea I have got so far is
#use if() to make it. How can I do it quickly?
#ideal result
>str
"abXdccc" "hijklccc" "abXuioccc"
答案 0 :(得分:3)
有点尴尬,但是您可以根据单个字符的值替换单个字符,例如:
ifelse(substr(str,3,3)=="c", `substr<-`(str,3,3,"X"), str)
#[1] "abXdccc" "hijklccc" "abXuioccc"
如果您乐意覆盖该值,则可以使其更整洁:
substr(str[substr(str,3,3)=="c"],3,3) <- "X"
str
#[1] "abXdccc" "hijklccc" "abXuioccc"
答案 1 :(得分:2)
我想知道您是否可以在这里使用正则表达式前瞻来获取所需内容。
str <- c("abcdccc","hijklccc","abcuioccc")
gsub("(^.{2})(?=c)(.*$)", "\\1X\\2", str, perl = T)
或使用最新邮件建议的正向后视
sub("(?<=^.{2})c", "X", str, perl = TRUE)
这是在寻找匹配c
的字母,该字母位于字符串开头的任何两个字符之后。 c
替换为X
。
(?<=
是积极回望的开始
^.{2}
表示从字符串开头的任意两个字符
)c
是最后一个部分,它必须在两个字符之后为c
[1] "abXcdccc" "hijklccc" "abXcuioccc"
如果您想了解有关正则表达式正在使用的更多信息(link)
另外一个通用函数:
switch_letter <- function(x, letter, position, replacement) {
stopifnot(position > 1)
pattern <- paste0("(?<=^.{", position - 1, "})", letter)
sub(pattern, replacement, x, perl = TRUE)
}
switch_letter(str, "c", 3, "X")
答案 2 :(得分:1)
您可以将ifelse
与gsub
一起使用,即
ifelse(substr(str, 3, 3) == 'c', paste0(substring(str, 1, 2),'X', substring(str, 4)), str)
#[1] "abXdccc" "hijklccc" "abXuioccc"
答案 3 :(得分:1)
这也应该起作用:
str <- c("abcdefg","hijklnm","abcuiowre")
a <- strsplit(str[1], "")[[1]]
a[3] <- "X"
a <- paste(a, collapse = '')
str[1] <- a
答案 4 :(得分:1)
这个主意如何?
c2Xon3 <- function(x){sprintf("%s%s%s",substring(x,1,3),gsub("c","X",substring(x,3,3)),substring(x,4,nchar(x)))}
str <- c("abcdccc","hijklccc","abcuioccc")
strNew <- sapply(str,c2Xon3 )
答案 5 :(得分:1)
这应该有效
g++ -o tree tree.cc `pkg-config --libs --cflags gtk+-2.0`