简体   繁体   English

Java split函数给了我一小段结果String数组

[英]Java split function gives me a small length of result String array

I have this code: 我有这个代码:

String string = "_a_b___";
String[] parts = string.split("_");

The result is that variable parts has only three elements 结果是可变部分只有三个元素

parts[0] = ""
parts[1] = "a" 
parts[2] = "b"

This is weird, because there are five "_" chars, so after splitting there should be six elements, not only three of them. 这很奇怪,因为有五个“_”字符,所以在分裂之后应该有六个元素,而不仅仅是三个元素。

I want 我想要

parts[0] = ""
parts[1] = "a"
parts[2] = "b"
parts[3] = ""
parts[4] = "" 
parts[5] = "" 

How to do that? 怎么做? Thank you very much! 非常感谢你!

From Java documentation :- Java文档 : -

Trailing empty strings are therefore not included in the resulting array. 因此,结尾的空字符串不包含在结果数组中。

Try split("_",6) 尝试split("_",6)

The solution of @Zakir is correct, i would add another information to use it perfectly, to get what you want instead of using split("_", 6) you can generalize it and use : @Zakir的解决方案是正确的,我会添加另一个信息来完美地使用它,以获得你想要的而不是使用split("_", 6)你可以概括它并使用:

String[] parts = string.split("_", string.replace("(?!_)", "").length());

Which can accept any length. 哪个可以接受任何长度。

for _a_b___ you will get [, a, b, , , ] 对于_a_b___你会得到[, a, b, , , ] _a_b___ [, a, b, , , ]


Edit 编辑

Or like @Bill F mention in comment, you can also use String[] parts = string.split("_", -1); 或者像@Bill F在评论中提到的那样,你也可以使用String[] parts = string.split("_", -1); for any length as well. 任何长度也是如此。 Java doc Java doc

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

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