Split a string by any number of spaces

混江龙づ霸主 提交于 2019-12-17 10:44:37

问题


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.


回答1:


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"  



回答2:


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

ss = "10012      ----      ----      ----      ----       CAB    UNCH                    CAB"

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

HTH



来源:https://stackoverflow.com/questions/24741541/split-a-string-by-any-number-of-spaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!