在第二个空格后插入新行

时间:2019-05-21 20:53:49

标签: r gsub

我正在尝试在第二个空格字符后插入新行。

如果我以字符串“ yellow red blue”开头

我希望它返回“黄色红色\ nblue”

2 个答案:

答案 0 :(得分:1)

我敢肯定有一种优雅的regex方式可以做到这一点,但这是一种骇人听闻的方式:

将所有空格替换为“ \ n”,然后再次用空格替换第一个“ \ n”。

mystring <- "yellow red blue"
library(stringr)
mystring %>%
  str_replace_all(" ", replacement = "\n") %>%
  str_replace("\n", " ")

答案 1 :(得分:0)

这项工作:

.init

word <- "yellow red blue" vect_word <- strsplit(word, " ")[[1]] paste(paste(vect_word[1:2], collapse = " "), "\n", vect_word[3:length(vect_word)], collapse = " ") 函数能够找到第二个空格。我的灵感是这篇文章:

Find the number of spaces in a string

相关问题