Use StringTokenizer to remove spaces from a string
Public classstringto { Public Static voidMain (string[] args) {String text= "We are students"; System.out.println ("The source string is:"); System.out.println (text); System.out.println (Text.trim ()); StringTokenizer St=NewStringTokenizer (Text, ""); StringBuffer SB=NewStringBuffer (); inti = 1; while(St.hasmoretokens ()) {i++; Sb.append (St.nexttoken ()); } System.out.println ("The string after removing all the spaces in the string is:"); System.out.println (Sb.tostring ()); }}
Mainly through the St.hasmoretokens implementation of the removal of space, then we observe the source:
Public StringTokenizer (String str, String Delim, Boolean returndelims) {
currentposition = 0;
Newposition =-1;
Delimschanged = false;
This.str = str;
Maxposition = Str.length ();
delimiters = Delim;
Retdelims = Returndelims;
Setmaxdelimcodepoint ();
}
Public BooleanHasmoretokens () {/** Temporarily store this position and use it on the following * NextToken () method only if the Delimi Ters Haven ' t been changed in * that NextToken () invocation. */newposition=skipdelimiters (currentposition); return(Newposition <maxposition); } Private intSkipdelimiters (intstartpos) { if(Delimiters = =NULL) Throw NewNullPointerException (); intPosition =startpos; while(!retdelims && Position <maxposition) { if(!hassurrogates) { Charc =Str.charat (position); if(C > Maxdelimcodepoint) | | (Delimiters.indexof (c) < 0)) Break; Position++; } Else { intc =Str.codepointat (position); if(C > Maxdelimcodepoint) | |!Isdelimiter (c)) { Break; } position+=Character.charcount (c); } } returnposition; }
Public String NextToken () {
/*
* If Next position already computed in hasmoreelements () and
* Delimiters has changed between the computation and this invocation,
* Then use the computed value.
*/
CurrentPosition = (newposition >= 0 &&!delimschanged)?
Newposition:skipdelimiters (currentposition);
/* Reset these anyway */
Delimschanged = false;
Newposition =-1;
if (currentposition >= maxposition)
throw new Nosuchelementexception ();
int start = currentposition;
CurrentPosition = Scantoken (currentposition);
Return str.substring (Start, currentposition);
}
The source code passes the length of the string, iterates through each character, compares the incoming character, and calls the substring method if it is the same as the character that needs to be intercepted.
Java method Summary and source code parsing (not to be continued)