【问题标题】:Shifting Strings using R functions使用 R 函数移动字符串
【发布时间】:2020-03-28 23:15:44
【问题描述】:

如何在 R 中移动字符串。 我有一个字符串“叶子”,当我左移时,结果应该是“跳蚤”。

我试过shift()函数。

但我无法理解如何对字符串的每个字母执行此操作。

谁能帮帮我

【问题讨论】:

    标签: r string letter


    【解决方案1】:

    您可以将以下解决方案与函数shifter(s,n)一起使用,其中n是要移位的位置数(可以是零,任何正整数或负整数,不限于字符串s的长度):

    shifter <- function(s, n) {
      n <- n%%nchar(s)
      if (n == 0) {
        s
      } else {
        paste0(substr(s,nchar(s)-n+1,nchar(s)), substr(s,1,nchar(s)-n))
      }
    }
    

    示例

    s <- "leaf"
    > shifter(s,0)
    [1] "leaf"
    
    > shifter(s,1) # shift to right by 1
    [1] "flea"
    
    > shifter(s,-1) # shift to left by 1
    [1] "eafl"
    

    【讨论】:

    • @KonradRudolph 感谢您提供的信息,然后我学习了它并更新了我的代码
    【解决方案2】:

    您可以将其转换为原始向量,并通过对最后一个和其余部分进行子集化来组合此向量。

    tt <- charToRaw("leaf")
    rawToChar(c(tt[length(tt)], tt[-length(tt)])) #Right shift
    #[1] "flea"
    
    rawToChar(c(tt[-1], tt[1])) #Left shift
    #[1] "eafl"
    

    如果您有扩展字符,您可以使用(感谢@KonradRudolph 的评论)

    tt <- strsplit("Äpfel", '')[[1L]]
    paste(c(tt[length(tt)], tt[-length(tt)]), collapse = "")  #Right shift
    #[1] "lÄpfe"
    
    paste0(c(tt[-1], tt[1]), collapse = "") #Left shift
    #[1] "pfelÄ"
    

    或使用utf8ToIntintToUtf8

    tt <- utf8ToInt("Äpfel")
    intToUtf8(c(tt[length(tt)], tt[-length(tt)]))
    #[1] "lÄpfe"
    
    intToUtf8(c(tt[-1], tt[1]))
    #[1] "pfelÄ"
    

    【讨论】:

    • 转换为 raw 和 back 的好主意。但是,请注意扩展字符。例如,这将使用诸如“Äpple”之类的字符串而失败。使用strsplit(s, '')[[1L]] 后跟paste 更安全(尽管代码更多)。
    • @KonradRudolph 非常感谢您的评论!我已将其包含在答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2021-03-14
    • 2021-10-04
    • 2011-03-17
    • 1970-01-01
    • 2011-09-18
    • 2020-02-16
    相关资源
    最近更新 更多