简体   繁体   English

Java字符串分割长度

[英]Java string split length

System.out.println("neon.mems.cmu.edu/people/".split("/").length); // output is 2

I was doing some url processing. 我正在做一些URL处理。 To my surprise I just got the result above. 令我惊讶的是,我刚得到上面的结果。 I thought the number of elements could be the number of splitters plus one. 我认为元素的数量可以是分离器的数量加一。

I didn't realize the last empty string(or just null ) is cut off from the splitted array until now. 我直到现在都没有意识到最后一个空字符串(或者只是null )是从拆分数组中删除的。 I wonder if this is the case with every programming language. 我想知道每种编程语言是否都是这种情况。

No that's not the case for every programming language and there is no universal specification so there is no reason it should be. 不,并非每种编程语言都如此,也没有通用规范,因此没有理由。

Go

a := strings.Split("neon.mems.cmu.edu/people/", "/")
fmt.Println(len(a)) // prints 3

Javascript Java脚本

Type this in the console of your browser : 在浏览器的控制台中输入以下内容:

"neon.mems.cmu.edu/people/".split('/')

The result is 结果是

["neon.mems.cmu.edu", "people", ""]

What you should do when a match is empty isn't something obvious or inherent to the split concept. 匹配为空时,您应该怎么做并不是split概念的明显内容或固有内容。 A proof of that is that old Internet Explorer versions did remove those empty matches . 一个证明是,旧的Internet Explorer版本确实删除了那些空匹配项

why it is discarded empty string? 为什么要丢弃空字符串?

String#split(regx) internally call String#split(regx,0) which execute Pattern.compile(regex).split(this, limit); String#split(regx)内部调用String#split(regx,0) ,该String#split(regx,0)执行Pattern.compile(regex).split(this, limit); actually - code snippet 实际上- 代码段

if (limit == 0)
        while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
            resultSize--;

where empty string has been discarded from resultSize if limit is 0. 如果limit为0,则从resultSize丢弃空字符串。

How to get desired result? 如何获得理想的结果?

String#split(regx,limit) use get desired result. String#split(regx,limit)使用可得到所需的结果。

System.out.println("neon.mems.cmu.edu/people/".split("/",3).length);

Result : 结果:

 3

And about language specification I am agree with @dystroy 关于语言规范,我同意@dystroy

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

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