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.
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.
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.
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"
strsplit function itself works, by simply using strsplit(ss, " +")
:
ss = "10012 ---- ---- ---- ---- CAB UNCH CAB" strsplit(ss, " +") [[1]] [1] "10012" "----" "----" "----" "----" "CAB" "UNCH" "CAB"
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With