【问题标题】:Insert blank space between letters of word在单词的字母之间插入空格
【发布时间】:2017-10-03 02:13:48
【问题描述】:

我正在尝试创建一个函数,该函数能够返回同一字符串的不同版本,但字母之间有空格。

类似:

input <- "word"

返回:

w ord
wo rd
wor d

【问题讨论】:

    标签: r regex string stringr


    【解决方案1】:

    我们首先使用strsplit 将字符串分解为每个字符。然后我们在每个位置使用sapply append 一个空白空间。

    input <- "word"
    input_break <- strsplit(input, "")[[1]]
    
    c(input, sapply(seq(1,nchar(input)-1), function(x)
                          paste0(append(input_break, " ", x), collapse = "")))
    
    #[1] "word"  "w ord" "wo rd" "wor d"
    

    ?append 给我们append(x, values, after = length(x)) 其中x 是向量,value 是要插入的值(此处为 " " ),after 是您要插入values 的位置。

    【讨论】:

      【解决方案2】:

      这是一个使用sub的选项

      sapply(seq_len(nchar(input)-1), function(i) sub(paste0('^(.{', i, '})'), '\\1 ', input))
      #[1] "w ord" "wo rd" "wor d"
      

      substring

      paste(substring(input, 1, 1:3), substring(input, 2:4, 4))
      #[1] "w ord" "wo rd" "wor d"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-18
        • 1970-01-01
        • 1970-01-01
        • 2019-10-14
        • 1970-01-01
        • 1970-01-01
        • 2012-10-08
        相关资源
        最近更新 更多