Java StringTokenizer get the first and last tokens example shows how to get the first token and last token from the StringTokenizer object.
How to get the first token from the StringTokenizer?
Getting the first token from the StringTokenizer object is fairly easy. After creating a tokenizer object, check if there is any token available using the hasMoreTokens
or hasMoreElements
method. If it returns true, get the first token using the nextToken
or nextElement
method.
Here is the code example for that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javacodeexamples.stringtokenizerexamples; import java.util.StringTokenizer; public class StringTokenizerGetFirstLastTokens { public static void main(String[] args) { String strData = "StringTokenizer get first token"; StringTokenizer st = new StringTokenizer(strData, " "); //always check if there is any token first if( st.hasMoreTokens() ) System.out.println("First token is: " + st.nextToken()); } } |
Output
1 |
First token is: StringTokenizer |
How to get the last token from the StringTokenizer object?
Getting the last token from the StringTokenizer object is not a straightforward thing to do. Since the StringTokenizer class does not provide any methods using which we can get a specific token by index, we need to iterate through all the tokens to get to the last one.
We are going to iterate through the string tokens using the hasMoreTokens
and nextToken
methods until there are no tokens left. See the below-given code example that does exactly that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.javacodeexamples.stringtokenizerexamples; import java.util.StringTokenizer; public class StringTokenizerGetFirstLastTokens { public static void main(String[] args) { String strData = "StringTokenizer get last token example"; StringTokenizer st = new StringTokenizer(strData, " "); String strLastToken = null; while( st.hasMoreTokens() ) { //this will hold the last token when loop completes strLastToken = st.nextToken(); } System.out.println("Last token is: " + strLastToken); } } |
Output
1 |
Last token is: example |
You may also want to know how to get the token ArrayList from the StringTokenizer or convert StringTokenizer to an array.
If you want to learn more about the tokenizer class, please visit the Java StringTokenizer Tutorial.
Please let me know your views in the comments section below.