Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by any number of spaces

Tags:

string

r

strsplit

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.

like image 274
Stu Avatar asked Jul 14 '14 16:07

Stu


People also ask

How do you split a string with spaces?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

How do I split a string into multiple parts?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.


2 Answers

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"   
like image 181
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 18 '22 15:09

A5C1D2H2I1M1N2O1R2T1


strsplit function itself works, by simply using strsplit(ss, " +"):

ss = "10012      ----      ----      ----      ----       CAB    UNCH                    CAB"  strsplit(ss, " +") [[1]] [1] "10012" "----"  "----"  "----"  "----"  "CAB"   "UNCH"  "CAB"   

HTH

like image 23
rnso Avatar answered Sep 22 '22 15:09

rnso