R语言中实现字符串大小写相互转换(大写转小写,小写转大写)
001、
test <- "jjUUaaBiJJ" ## 测试字符串 newstr <- "" for (i in 1:nchar(test)) { if (substr(test, i, i) %in% letters) { newstr <- paste0(newstr, toupper(substr(test, i, i))) } else { newstr <- paste0(newstr, tolower(substr(test, i, i))) } } newstr ## 结果
002、应用于向量
swap <- function(string){ newstr <- "" for (i in 1:nchar(string)) { if (substr(string, i, i) %in% letters) { newstr <- paste0(newstr, toupper(substr(string, i, i))) } else { newstr <- paste0(newstr, tolower(substr(string, i, i))) } } return(newstr) } test <- c("jjUUaaBiJJ", "aaBBccDeF", "eiJJmfF") ## 测试向量 newres <- vector() for (i in 1:length(test)) { newres <- c(newres, swap(test[i])) } newres ## 结果