Java字符串split方法的坑及解決
Java字符串split方法的坑
先來看幾行簡單的Java代碼,如下:
System.out.println("1,2".split(",").length);
System.out.println("1,2,".split(",").length);
System.out.println("".split(",").length);
System.out.println(",".split(",").length);接下來,猜一下各行的輸出結(jié)果。OK,下面給出真正的運(yùn)行結(jié)果:
2
2
1
0
這里先給出jdk相關(guān)源碼,再來對應(yīng)分析各自的輸出:
public String[] split(String regex, int limit) {
? ? /* fastpath if the regex is a
? ? ?(1)one-char String and this character is not one of the
? ? ? ? RegEx's meta characters ".$|()[{^?*+\\", or
? ? ?(2)two-char String and the first char is the backslash and
? ? ? ? the second is not the ascii digit or ascii letter.
? ? ?*/
? ? char ch = 0;
? ? if (((regex.value.length == 1 &&
? ? ? ? ?".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
? ? ? ? ?(regex.length() == 2 &&
? ? ? ? ? regex.charAt(0) == '\\' &&
? ? ? ? ? (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
? ? ? ? ? ((ch-'a')|('z'-ch)) < 0 &&
? ? ? ? ? ((ch-'A')|('Z'-ch)) < 0)) &&
? ? ? ? (ch < Character.MIN_HIGH_SURROGATE ||
? ? ? ? ?ch > Character.MAX_LOW_SURROGATE))
? ? {
? ? ? ? int off = 0;
? ? ? ? int next = 0;
? ? ? ? boolean limited = limit > 0;
? ? ? ? ArrayList<String> list = new ArrayList<>();
? ? ? ? while ((next = indexOf(ch, off)) != -1) {
? ? ? ? ? ? if (!limited || list.size() < limit - 1) {
? ? ? ? ? ? ? ? list.add(substring(off, next));
? ? ? ? ? ? ? ? off = next + 1;
? ? ? ? ? ? } else { ? ?// last one
? ? ? ? ? ? ? ? //assert (list.size() == limit - 1);
? ? ? ? ? ? ? ? list.add(substring(off, value.length));
? ? ? ? ? ? ? ? off = value.length;
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? // If no match was found, return this
? ? ? ? if (off == 0)
? ? ? ? ? ? return new String[]{this};
?
? ? ? ? // Add remaining segment
? ? ? ? if (!limited || list.size() < limit)
? ? ? ? ? ? list.add(substring(off, value.length));
?
? ? ? ? // Construct result
? ? ? ? int resultSize = list.size();
? ? ? ? if (limit == 0) {
? ? ? ? ? ? while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
? ? ? ? ? ? ? ? resultSize--;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? String[] result = new String[resultSize];
? ? ? ? return list.subList(0, resultSize).toArray(result);
? ? }
? ? return Pattern.compile(regex).split(this, limit);
}1.第一行代碼的輸出結(jié)果肯定沒什么問題,字符串 "1,2" 以 "," 分隔,結(jié)果很直觀的是 ["1", "2"],length=2。
2.第二行代碼的輸出結(jié)果,可能大家有人認(rèn)為是length=3才對,因?yàn)樽址?"1,2," 以 "," 分隔,結(jié)果應(yīng)該是 ["1", "2", ""],length=3;其實(shí)不然,jdk在split處理的時候,確實(shí)會先生成一個集合list = ["1", "2", ""],但之后卻會循環(huán)判斷末位元素是否為空字符串(即末位元素length=0),因此集合最終會變成 ["1", "2"],length=2。具體判斷如下:
while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
? ? resultSize--;
}3.第三行代碼的輸出結(jié)果,數(shù)組 [""],length=1。與其他三種情況不同,空字符串 "" 中不包含regex字符串 ",",所以代表沒有匹配上的子串(off=0),則返回字符串本身。具體處理如下:
// If no match was found, return this
if (off == 0)
? ? return new String[]{this};4.第四行代碼的輸出結(jié)果,可能也有部分人認(rèn)為結(jié)果應(yīng)是length=2,因?yàn)樽址?"," 以 "," 分隔,結(jié)果應(yīng)該是 ["", ""],length=2;其實(shí)亦不然,與第2行同樣的原理,最終將list=["", ""] 處理為空集合 [],length=0。
以上,系本文分享的split的一個小坑;除此之外,另一個需要注意的地方,split方法的參數(shù)是正則表達(dá)式而非一般字符串,所以在處理正則轉(zhuǎn)義字符和特殊字符時留意即可。
Java字符串split方法的探究
今天在使用split分割字符串時突然想到一種情況,如下:
String str="aaaaaaaab";
String arr[]=str.split("aa");
問,arr數(shù)組的長度是多少?
那如果str為”baaaaaaaa”呢
String str="baaaaaaaa";
如果str=”aaaaaaaab”呢
String str="aaaaaaaab";
如果str=”baaaaaaaab”呢
String str="baaaaaaaab";
好,我們先在程序中驗(yàn)證一下:
public class Test {
public static void main(String[] args) {
String str="aaaaaaaa";
String [] arr=str.split("aa");
System.out.println("字符串a(chǎn)aaaaaaa分割的數(shù)組長度為:"+arr.length);
str="baaaaaaaa";
arr=str.split("aa");
System.out.println("字符串baaaaaaaa分割的數(shù)組長度為:"+arr.length);
str="aaaaaaaab";
arr=str.split("aa");
System.out.println("字符串a(chǎn)aaaaaaab分割的數(shù)組長度為:"+arr.length);
str="baaaaaaaab";
arr=str.split("aa");
System.out.println("字符串baaaaaaaab分割的數(shù)組長度為:"+arr.length);
}
}
運(yùn)行以上代碼輸出結(jié)果

看到結(jié)果的你是不是有點(diǎn)小小的驚訝,如果有的話那就繼續(xù)往下看。
通過split方法查看源碼可知又調(diào)用了split(regex, 0)方法并且傳入一個0:
public String[] split(String regex) {
return split(regex, 0);
}
繼續(xù)查看源碼
public String[] split(String regex, int limit) {
/* fastpath if the regex is a
(1)one-char String and this character is not one of the
RegEx's meta characters ".$|()[{^?*+\\", or
(2)two-char String and the first char is the backslash and
the second is not the ascii digit or ascii letter.
*/
char ch = 0;
if (((regex.value.length == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == 0) {
while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
resultSize--;
}
}
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
return Pattern.compile(regex).split(this, limit);
}
有其中關(guān)系可知最終會執(zhí)行 Pattern.compile(regex).split(this, limit)這一段代碼,基礎(chǔ)往下扒代碼:
public String[] split(CharSequence input, int limit) {
int index = 0;
boolean matchLimited = limit > 0;
ArrayList<String> matchList = new ArrayList<>();
Matcher m = matcher(input);
// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < limit - 1) {
if (index == 0 && index == m.start() && m.start() == m.end()) {
// no empty leading substring included for zero-width match
// at the beginning of the input char sequence.
continue;
}
String match = input.subSequence(index, m.start()).toString();
matchList.add(match);
index = m.end();
} else if (matchList.size() == limit - 1) { // last one
String match = input.subSequence(index,
input.length()).toString();
matchList.add(match);
index = m.end();
}
}
// If no match was found, return this
if (index == 0)
return new String[] {input.toString()};
// Add remaining segment
if (!matchLimited || matchList.size() < limit)
matchList.add(input.subSequence(index, input.length()).toString());
// Construct result
int resultSize = matchList.size();
if (limit == 0)
while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
resultSize--;
String[] result = new String[resultSize];
return matchList.subList(0, resultSize).toArray(result);
}
通過代碼我們可以發(fā)現(xiàn)最終matchList集合中會有值,不過都是空值,然后在
while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
resultSize--;
這一段代碼中,首先判斷最后一個是不是空,如果沒有值的話就減一位,依次類推,所以看到這大家對以上程序出現(xiàn)的結(jié)果是不是就不奇怪了。
所以我們可以大膽的總結(jié)一下,使用split方法分割字符串,如果最后幾位是空的話,會將空的位置去掉。
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring boot 自定義規(guī)則訪問獲取內(nèi)部或者外部靜態(tài)資源圖片的方法
這篇文章主要介紹了spring boot 自定義規(guī)則訪問獲取內(nèi)部或者外部靜態(tài)資源圖片的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
springmvc中RequestMappingHandlerAdapter與HttpMessageConverter的
今天小編就為大家分享一篇關(guān)于springmvc中RequestMappingHandlerAdapter與HttpMessageConverter的裝配講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
SpringBoot+Security 發(fā)送短信驗(yàn)證碼的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot+Security 發(fā)送短信驗(yàn)證碼的實(shí)現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
Java Annotation(Java 注解)的實(shí)現(xiàn)代碼
本篇文章介紹了,Java Annotation(Java 注解)的實(shí)現(xiàn)代碼。需要的朋友參考下2013-05-05
feign遠(yuǎn)程調(diào)用無法傳遞對象屬性405的問題
這篇文章主要介紹了feign遠(yuǎn)程調(diào)用無法傳遞對象屬性405的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot 中實(shí)現(xiàn)跨域的5種方式小結(jié)
這篇文章主要介紹了SpringBoot 中實(shí)現(xiàn)跨域的5種方式小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02

