例如
String splits[] = ("||").split("[|]")
System.out.println(splits.length)
返回 0。而我预计它会返回 2。解决此问题的最佳方法是什么?
最佳答案
split()
的默认操作是丢弃尾随的空字符串。由于每个结果字符串都是空的,因此不会返回任何字符串。
更准确地说,调用 split(String)
与调用 split(String, int)
相同第二个参数设置为0。
0 表示(强调我的):
... the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
如果你想保留尾随空字符串(并且不想限制元素的数量),那么传入一个负值(我建议 -1):
String splits[] = "||".split("\\|", -1);
关于java - string.split 如何评估只有分隔符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10908803/