java.util.StringTokenizer.nextToken()
Description
This method is actively being used hand in hand with hasMoreTokens() method. When this two method are combined together, we will have a way to effectively traverse throughout the tokens.
Method Syntax
public String nextToken()
throws
NoSuchElementException – if there are no more tokens in this tokenizer’s string.
Method Returns
The nextToken() method returns the next token from this string tokenizer.
Compatibility
Requires Java 1.0 and up
Java STringTokenizer nextToken() Example
Below is a java code demonstrates the use of nextToken() method of StringTokenizer class. The example presented might be simple however it shows the behaviour of the nextToken() method. Basically we have a string declared initially and as you can see it’s actually a group of string delimited by “|” pipe. And we used StringTokenizer to break it down into tokens. This will transform the String into a more meaningful information on this case, we presented the first token as string, then the second as age, etc.
package com.javatutorialhq.java.examples; import java.util.StringTokenizer; /* * This example source code demonstrates the use of * nextToken() method of StringTokenizer class. * */ public class StringTokenizerNextTokenExample { public static void main(String[] args) { //declare a new String with tokens delimited by | String str = "Vince|2|Male|Paya Lebar, Singapore"; /* * initialize our StringTokenizer using input * as source String and | as the delimiter */ StringTokenizer st = new StringTokenizer(str,"|"); String name = st.nextToken(); String age = st.nextToken(); String gender = st.nextToken(); String address = st.nextToken(); System.out.println("Name:"+name); System.out.println("Age:"+age); System.out.println("Gender:"+gender); System.out.println("Address:"+address); } }