解析字符串:空元素来自哪里?

时间:2013-06-12 20:32:58

标签: r

请告诉我,解析字符串后为什么矢量中有空元素?

我输入的内容:

a <- "--key1 = value1 --key2 = value2 --key3 = value3 --switch.1 --switch.2"
unlist(strsplit(a, split = "--"))

我得到了什么:

[1] ""               "key1 = value1 " "key2 = value2 " "key3 = value3 "
[5] "switch.1 "      "switch.2"

还有一个问题:是否可以只从矢量中选择那些在其中包含“=”(任何特定字母)的元素?

提前谢谢!

2 个答案:

答案 0 :(得分:4)

您将字符串拆分为"--"作为分隔符。由于输入字符串中的第一个字符是"--",因此从概念上讲,您首先是空子字符串,然后是分隔符,然后是字符串的其余部分,等等。这就是为什么结果数组中的第一个元素是空字符串的原因

答案 1 :(得分:3)

来自?strsplit

 repeat {
    if the string is empty
        break.
    if there is a match
        add the string to the left of the match to the output.
        remove the match and all to the left of it.
    else
        add the string to the output.
        break.
}

所以第一个条目左侧有"",这就是你选择它的原因。您可以在!=""上拆分后始终进行子集化。