从 String#split 返回的零长度字符串 [英] Zero-length string being returned from String#split

查看:53
本文介绍了从 String#split 返回的零长度字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 1.9.3(可能还有更早的版本,不确定)中,我试图弄清楚为什么 Ruby 的 String#split 方法会给我某些结果.我得到的结果似乎与我的预期相反.举个例子:

In Ruby 1.9.3 (and probably earlier versions, not sure), I'm trying to figure out why Ruby's String#split method is giving me certain results. The results I'm getting seem counter-intuitive from what I would expect. Here's an example:

"abcabc".split("b") #=> ["a", "ca", "c"]
"abcabc".split("a") #=> ["", "bc", "bc"]
"abcabc".split("c") #=> ["ab", "ab"]

在这里,第一个示例完全返回了我的预期.

Here, the first example returns exactly what I would expect.

但是在第二个例子中,我很困惑为什么#split 返回一个长度为零的字符串作为返回数组的第一个值.这是什么原因?这正是我所期望的:

But in the second example, I'm confused as to why #split is returning a zero-length string as the first value of the returned array. What is the reasoning for this? This is what I would expect instead:

"abcabc".split("a") #=> ["bc", "bc"]

沿着同一行,为什么在第三个示例中没有返回尾随零长度字符串?如果第二个示例返回一个长度为零的字符串作为它的第一个值,那么最后一个示例应该返回与它的最后一个值相同的值.

And along that same line, how come there is no trailing zero-length string returned in the third example? If the second example returns a zero-length string as it's first value, then the last example should return the same as it's last value.

启发我,我在这里错过了什么??

Enlighten me, what am I missing here??

编辑:深入研究它,我意识到为什么这是默认行为以及为什么我的想法是完全错误的.例如,如果我们要查看 CSV 文件,在每一列上拆分,我们的数据将被丢弃,因为空的前导列将被忽略.

EDIT: Looking more into it, I realize why this is the default behavior and why my thinking is completely wrong. If we were to go through a CSV file for example, splitting on each column, our data would be thrown off because empty leading columns would be ignored.

另外需要注意的是,这个问题不仅仅与 Ruby 相关——我了解到许多其他语言的行为方式完全相同.当我知道这件事时,我只是在使用 Ruby.

Also it's important to note that this question isn't related to only Ruby--I'm learning that many other languages behave in the exact same manner. I was simply using Ruby when I learned of this.

推荐答案

"abcabc".split("b") #=> ["a", "ca", "c"]
"abcabc".split("a") #=> ["", "bc", "bc"]
"abcabc".split("c") #=> ["ab", "ab"]

假设你用逗号分隔.你期望从什么行为",bc,bc".split(',')?在'a'上拆分没有什么不同.对于第三个示例,split 默认省略尾随空字符.

Suppose you were splitting on a comma. What behaviour would you expect from ",bc,bc".split(',')? It's not different with splitting on 'a'. For the third example, split omits the trailing empties by default.

这篇关于从 String#split 返回的零长度字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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