用任意数量的空格分割一个字符串 [英] Split a string by any number of spaces

查看:37
本文介绍了用任意数量的空格分割一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

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

我想通过间隙分割这个字符串,但间隙有可变数量的空格.有没有办法使用 strsplit() 函数来分割这个字符串并返回一个由 8 个元素组成的向量,这个向量已经去除了所有的间隙?

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\\s+ 即可拆分:

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

<小时>

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

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

这篇关于用任意数量的空格分割一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆