+-
Java将字符串拆分为数组
参见英文答案 > Java String split removed empty values                                    6个
我需要split()方法的帮助.
我有以下字符串:

String values = "0|0|0|1|||0|1|0|||";

我需要将值放入数组中.有3种可能的字符串:“0”,“1”和“”

我的问题是,当我尝试使用split()时:

String[] array = values.split("\\|"); 

我的值只保存到最后0.看起来像“|||”部分被修剪.
我究竟做错了什么?

谢谢

最佳答案
此行为在 String.split(String regex)中明确记录(强调我的):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

如果你想要包含那些尾随空字符串,你需要使用String.split(String regex, int limit)和第二个参数(限制)的负值:

String[] array = values.split("\\|", -1);
点击查看更多相关文章

转载注明原文:Java将字符串拆分为数组 - 乐贴网