Andrew Taylor
Andrew Taylor

Reputation: 3488

strsplit() behaves different with space at the beginning and end of string

Depending on if the split criteria (' ') is at the beginning or end of a string, it shows up as an item in the output list.

#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"

Is there a way to alter this code so that the space shows up as an item for both lists?

Intended output:

#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"

Upvotes: 2

Views: 108

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

Use 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"

Upvotes: 4

Related Questions