Java Split method source code Analysis
1 PublicString[] Split (charsequence input [,intlimit]) {2 intindex = 0;//Pointers3 Booleanmatchlimited = limit > 0;//whether to limit the number of matches4Arraylist<string> matchlist =NewArraylist<string> ();//Match result Queue5Matcher m = Matcher (input);//The character to be cut (string) matches the object, where is the pattern? 6 7 //ADD segments before each match found8 while(M.find ()) {9 if(!matchlimited | | matchlist.size () < limit-1) {//If you do not limit the number of matches or the current result list size is less than limit-1TenString match = input.subsequence (index, M.start ()). ToString ();//take a substring, (the position of the pointer, the first place in which the string is separated) OneMatchlist.add (match);//add to result set Aindex = M.end ();//Move Pointer -}Else if(matchlist.size () = = limit-1) {//last one, that's all that's left. -String match = input.subsequence (index, Input.length ()). ToString ();//The last element is taken from the pointer to the end of the string the Matchlist.add (match); -index =m.end (); - } - } + - //If no match is found, return this + if(index = = 0)//that is, it doesn't mean to slice it, it returns the whole string. A return Newstring[] {input.tostring ()}; at - //ADD remaining segment - if(!matchlimited | | matchlist.size () < limit)//if the number of matches is not limited or the result set size is less than the limit - //At this time, there are no matches, such as __1_1___, to take the last 1 of the following part -Matchlist.add (input.subsequence (Index, Input.length ()). ToString ());//The last element is taken from the pointer to the end of the string - in //Construct Result - intResultSize =matchlist.size (); to if(Limit = = 0) + while(resultsize > 0 && matchlist.get (resultSize-1). Equals (""))//if the final element of the result set is "", delete them one by one -resultsize--; theString[] result =NewString[resultsize]; * returnMatchlist.sublist (0, resultsize). ToArray (result); $}
In particular, in the last while loop, the final "" element of the result set is removed, and someone asks "Boo:and:foo" to split with "O", why the result is {"B", "" ",": And:f "} instead of {" B "," ",": And:f "," "," "} The reason for the problem.
Java Split method source code Analysis