Given a lower case string. Ex:
s <- 'abcdefghijklmnopqrstuvwxyz'
The goal is to make every other vowel in the string an uppercase.
Desired output here:
abcdEfghijklmnOpqrstuvwxyz
As you can see, since all vowels where used in order, e
and o
where uppercase.
There are only lowercase characters in the strings in all cases.
For aieou
, the desired output is:
aIeOu
How could I do this?
I tried:
s[unlist(strsplit(s, '')) %in% c('a', 'e', 'i', 'o', 'u')] <- toupper(s[unlist(strsplit(s, '')) %in% c('a', 'e', 'i', 'o', 'u')])
But no avail.
CodePudding user response:
It's not a one-liner, but:
s <- 'abcdefghijklmnopqrstuvwxyz'
as_list <- unlist(strsplit(s, ''))
vowels <- as_list %in% c('a', 'e', 'i', 'o', 'u')
every_other_index <- which(vowels)[c(FALSE, TRUE)]
as_list[every_other_index] <- toupper(as_list[every_other_index])
print(paste(as_list, collapse=''))
gives:
[1] "abcdEfghijklmnOpqrstuvwxyz"
(Use of which
taken from this question; use of c(FALSE, TRUE)]
from here.)
CodePudding user response:
Using gsub
, Replacement
s <- 'abcdefghijklmnopqrstuvwxyz'
gsub('(e|o)', '\\U\\1', s, perl=TRUE)
# [1] "AbcdEfghIjklmnOpqrstUvwxyz"
gsub('(e|o)', '\\U\\1', 'Hello World', perl=TRUE)
# [1] "HEllO WOrld"