Split a string by any number of spaces

Stu picture Stu · Jul 14, 2014 · Viewed 42.9k times · Source

I have the following string:

[1] "10012      ----      ----      ----      ----       CAB    UNCH                    CAB"

I want to split this string by the gaps, but the gaps have a variable number of spaces. Is there a way to use strsplit() function to split this string and return a vector of 8 elements that has removed all of the gaps?

One line of code is preferred.

Answer

A5C1D2H2I1M1N2O1R2T1 picture A5C1D2H2I1M1N2O1R2T1 · Jul 14, 2014

Just use strsplit with \\s+ to split on:

x <- "10012      ----      ----      ----      ----       CAB    UNCH       CAB"
x
# [1] "10012      ----      ----      ----      ----       CAB    UNCH       CAB"
strsplit(x, "\\s+")[[1]]
# [1] "10012" "----"  "----"  "----"  "----"  "CAB"   "UNCH"  "CAB"  
length(.Last.value)
# [1] 8

Or, in this case, scan also works:

scan(text = x, what = "")
# Read 8 items
# [1] "10012" "----"  "----"  "----"  "----"  "CAB"   "UNCH"  "CAB"