The substring method in Java can decompose a string and return a substring of the original string. If you want to tell a string to be broken down into one word or tag, StringTokenizer can help you.
Let's look at an example:
1publicstaticvoid main (string[] Args) { 2 new StringTokenizer ("www.ooobj.com", ". b"); 3 while (st.hasmoreelements ()) { 4 System.out.println ("Token:" + st.nexttoken ()); 5 } 6 }
Output:
Token:www
Token:ooo
Token:j
Token:com
There are two common methods of stringtokenizer:
1.hasMoreElements (). This method is the same as the use of the hasmoreelements () method, except that the method implemented by StringTokenizer to implement the enumeration interface can be seen from the StringTokenizer declaration: class StringTokenizer Implements Enumeration<object>.
2.nextElement (). This method is the same as the Nexttoken () method, and returns the next token for this stringtokenizer.
Three construction methods for Stringtokenizer:
1.StringTokenizer (String str). The default is "\t\n\r\f" (there is a space before, the quotation marks are not) as the Delimiter.
Source:
Public StringTokenizer (String Str) {
This (str, "\t\n\r\f", false);
}
Instance:
[java]View PlainCopyprint?
- Public static void main (string[] Args) {
- StringTokenizer st = New StringTokenizer ("www ooobj com");
- while (st.hasmoreelements ()) {
- System.out.println ("Token:" + st.nexttoken ());
- }
- }
Output:
Token:www
Token:ooobj
Token:com
2.StringTokenizer (string str, String delim). Specify Delim as the separator, see the first Example.
3.StringTokenizer (string str, string delim, boolean returndelims). Returndelims is true, the Delim delimiter is also considered a marker.
Instance:
public static void main (string[] Args) {
StringTokenizer st = new StringTokenizer ("www.ooobj.com", ".", true);
While (st.hasmoreelements ()) {
System.out.println ("Token:" + st.nexttoken ());
}
}
Output:
Token:www
Token:.
Token:ooobj
Token:.
Token:com
Java string decomposition StringTokenizer usage