【问题标题】:strsplit() behaves different with space at the beginning and end of stringstrsplit() 的行为与字符串开头和结尾处的空格不同
【发布时间】:2015-11-11 22:26:31
【问题描述】:

根据拆分条件 (' ') 是在字符串的开头还是结尾,它会在输出列表中显示为一个项目。

#strsplit("This is a string ")

strsplit("This is a string ", ' ')
#[[1]]
#[1] "This"   "is"     "a"      "string"

#strsplit(" And this is a string", ' ')
strsplit(" And this is a string", ' ')
#[[1]]
#[1] ""       "And"    "this"   "is"     "a"      "string"

有没有办法更改此代码,以便空间显示为两个列表的项目?

预期输出:

#strsplit("This is a string ")

strsplit("This is a string ", ' ')
#[[1]]
#[1] "This"   "is"     "a"      "string" "" 

#strsplit(" And this is a string", ' ')
strsplit(" And this is a string", ' ')
#[[1]]
#[1] ""       "And"    "this"   "is"     "a"      "string"

【问题讨论】:

  • 请注意,这是在“详细信息”部分中?strsplit 记录的行为。

标签: r strsplit


【解决方案1】:

使用stringi::stri_split

require(stringi)
stri_split_fixed("This is a string ", ' ')
#[[1]]
#[1] "This"   "is"     "a"      "string" ""      

stri_split_fixed(" And this is a string", ' ')
#[[1]]
#[1] ""       "And"    "this"   "is"     "a"     
#[6] "string"

【讨论】:

  • library(ore); ore.split(" ", "this is a string ")
猜你喜欢
  • 2021-03-22
  • 1970-01-01
  • 2019-11-06
  • 2011-03-01
  • 2011-12-22
  • 2012-10-27
  • 2013-10-07
  • 2021-09-27
  • 1970-01-01
相关资源
最近更新 更多