string 用任意数量的空格分割一个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24741541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:19:51  来源:igfitidea点击:

Split a string by any number of spaces

rstringstrsplit

提问by Stu

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?

我想通过间隙分割这个字符串,但间隙有可变数量的空格。有没有办法使用strsplit()函数来分割这个字符串并返回一个包含 8 个元素的向量,该向量已删除所有间隙?

One line of code is preferred.

一行代码是首选。

回答by A5C1D2H2I1M1N2O1R2T1

Just use strsplitwith \\s+to split on:

只需使用strsplitwith\\s+即可拆分:

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, scanalso works:

或者,在这种情况下,scan也有效:

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

回答by rnso

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

strsplit 函数本身可以工作,只需使用strsplit(ss, " +")

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

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

HTH

HTH