【问题标题】:Making every other vowel in a vector uppercase使向量中的每个其他元音大写
【发布时间】:2022-01-02 07:38:40
【问题描述】:

给定一个小写字符串。例如:

s <- 'abcdefghijklmnopqrstuvwxyz'

目标是使字符串中的每个其他元音都大写。

此处需要的输出:

abcdEfghijklmnOpqrstuvwxyz

如您所见,由于所有元音按顺序使用,eo 大写。

在所有情况下,字符串中只有小写字符。

对于aieou,所需的输出是:

aIeOu

我怎么能在 R 中做到这一点?

我试过了:

s[unlist(strsplit(s, '')) %in% c('a', 'e', 'i', 'o', 'u')] <- toupper(s[unlist(strsplit(s, '')) %in% c('a', 'e', 'i', 'o', 'u')])

但无济于事。

即使这样有效,也不会是所有其他元音

R 版本 4.1.1。

【问题讨论】:

    标签: r string uppercase


    【解决方案1】:

    这不是单行,而是:

    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=''))
    

    给予:

    [1] "abcdEfghijklmnOpqrstuvwxyz"
    

    (使用取自this questionwhich;使用c(FALSE, TRUE)]from here。)

    【讨论】:

    • 有效!!!非常感谢,不知道 R 中的切片可以重复(使用c(FALSE, TRUE))。
    【解决方案2】:

    另一种可能的解决方案,使用stringrpurrr::map2

    library(tidyverse)
    
    s <- 'abcdefghijklmnopqrstuvwxyz'
    
    s %>% 
      str_split("") %>% unlist %>% 
      map2({1:nchar(s) %in% (str_which(.,"[aeiou]") %>% .[c(F,T)])},
           ~ if_else(.y, str_to_upper(.x),.x)) %>% 
      str_c(collapse = "")
    
    #> [1] "abcdEfghijklmnOpqrstuvwxyz"
    

    【讨论】:

    • 它不会在每个 other 元音上都这样做。
    • 感谢@U12-Forward 提醒我注意这一点。我误读了您最初的问题 - 每隔 other 错过了一部分......我将调整我的解决方案以符合这一要求。
    • 我新编辑的解决方案可以满足您的需求,@U12-Forward。
    【解决方案3】:

    使用gregexpr,然后使用gsub,以及\\Uppercase 模式替换。

    f <- function(s, u=c('a', 'e', 'i', 'o', 'u')) {
      v <- sort(unlist(sapply(u, \(u) all(unlist(gregexpr(u, s)) > -1))))
      v <- v[seq_along(v) %% 2 == 0]
      gsub(sprintf('(%s)', paste(names(v[v]), collapse='|')), '\\U\\1', s, perl=TRUE)
    }
    
    f('abcdefghijklmnopqrstuvwxyz')
    # [1] "abcdEfghijklmnOpqrstuvwxyz"
    
    f('world hello')
    # [1] "world hEllo"
    
    f('hello world')
    # [1] "hEllo world"
    

    【讨论】:

    • 这行不通,因为如果元音的顺序不同或者不是所有的元音都被使用,eo 就不会是假定为大写的元音。
    • 不适用于Hello World
    • @U12 我不确定你的意思是什么,我错过了一些逻辑吗?
    • Helloworld 应该是HellO WorldWorld Hello 应该是World HEllo
    • 编辑了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多