Java String 的 split 方法忽略空子串 [英] Java String's split method ignores empty substrings
问题描述
今天我发现java String.split()
的行为很奇怪.
It occured to me today the behavior of java String.split()
is very strange.
实际上我想通过 .split(",")
将字符串 "aa,bb,cc,dd,,,ee"
拆分为数组,这给了我一个字符串数组 ["aa","bb","cc","dd","","","ee"]
长度为 7.
Actually I want to split a string "aa,bb,cc,dd,,,ee"
to array by .split(",")
that gives me a String array ["aa","bb","cc","dd","","","ee"]
of length 7.
但是当我尝试将字符串 "aa,bb,cc,dd,,,,"
拆分为数组时,这给了我一个长度为 4 的数组,这意味着只有 ["aa","bb","cc","dd"]
拒绝所有接下来的空白字符串.
But when I try to split a String "aa,bb,cc,dd,,,,"
to array this gives me a array of length 4 means only ["aa","bb","cc","dd"]
rejecting all next blank Strings.
我想要一个将像 "aa,bb,cc,dd,,,,"
这样的字符串拆分为数组 ["aa","bb","cc","dd","","",""]
.
I want a procedure that splits a String like "aa,bb,cc,dd,,,,"
to array ["aa","bb","cc","dd","","",""]
.
这可以用 java.lang.String api 实现吗?提前致谢.
Is this possible with java.lang.String api? Thanks in advance.
推荐答案
使用 String.split(String regex, int limit)
带有负限制(例如 -1).>
"aa,bb,cc,dd,,,,".split(",", -1)
当 String.split(String regex)
被调用,它被调用时limit
= 0,这将删除数组中所有尾随的空字符串(在大多数情况下)案例,见下文).
When String.split(String regex)
is called, it is called with limit
= 0, which will remove all trailing empty strings in the array (in most cases, see below).
String.split(String regex)
的实际行为相当混乱:
The actual behavior of String.split(String regex)
is quite confusing:
- 拆分空字符串将生成长度为 1 的数组.拆分空字符串将始终生成包含空字符串的长度为 1 的数组.
- 将
";"
或";;;"
与regex
拆分为";"
将导致一个空数组.非空字符串拆分将导致删除数组中的所有尾随空字符串.
- Splitting an empty string will result in an array of length 1. Empty string split will always result in length 1 array containing the empty string.
- Splitting
";"
or";;;"
withregex
being";"
will result in an empty array. Non-empty string split will result in all trailing empty strings in the array removed.
至少从 Java 5 到 Java 8 都可以观察到上述行为.
The behavior above can be observed from at least Java 5 to Java 8.
尝试更改在 JDK-6559590.然而,它很快在 JDK-8028321 中被恢复,因为它在各个地方导致回归.该更改从未包含在最初的 Java 8 版本中.
There was an attempt to change the behavior to return an empty array when splitting an empty string in JDK-6559590. However, it was soon reverted in JDK-8028321 when it causes regression in various places. The change never makes it into the initial Java 8 release.
这篇关于Java String 的 split 方法忽略空子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!