["test", "one", "two"] 对,完美。正是我们想要的。 "test..two".split(".") # => -6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:22:26 24 4
gpt4 key购买 nike

检查:

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

对,完美。正是我们想要的。

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

我将 one 替换为空字符串,这样才有意义

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

这就是我所期望的,这里没有问题。

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

是的,我的字符串有一个 . 所以我得到了两个部分。

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

什么?我的字符串中有一个 .,它应该被分成两部分。我没有要求摆脱空字符串;它没有在测试 2 或 4 中删除空字符串。
我本以为 ["test", ""]

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

什么?这应该几乎完全像测试 3 一样运行,并返回 [""]。但现在我无法对 result[0]

执行任何字符串方法

为什么这对于发生在边缘或空字符串上的拆分不一致?

最佳答案

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

If the limit parameter is omitted, trailing null fields are suppressed. 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). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

所以,这符合您的预期:

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

其余部分在文档中。

关于ruby - 为什么拆分字符串不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29852905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com