简体   繁体   English

为什么拆分字符串不一致?

[英]Why is splitting strings inconsistent?

Examine: 检查:

"test.one.two".split(".") # => ["test", "one", "two"]

Right, perfect. 对,完美。 Exactly what we want. 正是我们想要的。

"test..two".split(".") # => ["test", "", "two"]

I replaced one with the empty string, so that makes sense 我用空字符串替换了one ,这很有意义

"test".split(".") # => ["test"]

That's what I would expect, no problems here. 这就是我所期望的,这里没有问题。

".test".split(".") # => ["", "test"]

Yep, my string has one . 是的,我的绳子有一根. so I got two sections as a result. 因此,我得到了两个部分。

"test.".split(".") # => ["test"]

What? 什么? There's a . 有一个. in my string, it should have been split into two sections. 在我的字符串中,应该将其分为两部分。 I didn't ask to get rid of empty strings; 我并没有要求摆脱空字符串。 it didn't get rid of empty strings back in tests 2 or 4. 在测试2或4中并没有消除空字符串。
I would have expected ["test", ""] 我本来希望["test", ""]

"".split(".") # => []

WHAT? 什么? This should operate almost exactly like test 3, and return [""] . 该操作应几乎与测试3 完全一样,并返回[""] But now I can't perform any string methods on result[0] 但是现在我无法对result[0]执行任何字符串方法

Why is this inconsistent for splits that occur on the edges, or for the empty string? 为什么这对于边缘上发生的拆分或空字符串而言不一致?

The documentation explains this well: http://ruby-doc.org/core-2.2.0/String.html#method-i-split 该文档对此进行了很好的解释: http : //ruby-doc.org/core-2.2.0/String.html#method-i-split

If the limit parameter is omitted, trailing null fields are suppressed. 如果省略limit参数,则尾随空字段将被抑制。 If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). 如果limit为正数,则最多将返回该字段数(如果limit为1,则整个字符串将作为数组中的唯一条目返回)。 If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed. 如果为负,则返回的字段数没有限制,尾随的空字段也不会被抑制。

So, this does what you'd expect: 因此,这符合您的期望:

"test.".split(".", -1)
 => ["test", ""]

The rest is there in the docs. 其余的都在文档中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM