StringTokenizer class in java
The StringTokenizer is a built-in class in java used to break a string into tokens. The StringTokenizer class is available inside the java.util package.
The StringTokenizer class object internally maintains a current position within the string to be tokenized.
🔔 A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
The StringTokenizer class in java has the following constructor.
S. No. | Constructor with Description |
---|---|
1 |
StringTokenizer(String str)
It creates StringTokenizer object for the specified string str with default delimeter. |
2 |
StringTokenizer(String str, String delimeter)
It creates StringTokenizer object for the specified string str with specified delimeter. |
3 |
StringTokenizer(String str, String delimeter, boolean returnValue)
It creates StringTokenizer object with specified string, delimeter and returnValue. |
The StringTokenizer class in java has the following methods.
S.No. | Methods with Description |
---|---|
1 |
String nextToken()
It returns the next token from the StringTokenizer object. |
2 |
String nextToken(String delimeter)
It returns the next token from the StringTokenizer object based on the delimeter. |
3 |
Object nextElement()
It returns the next token from the StringTokenizer object. |
4 |
boolean hasMoreTokens()
It returns true if there are more tokens in the StringTokenizer object. otherwise returns false. |
5 |
boolean hasMoreElements()
It returns true if there are more tokens in the StringTokenizer object. otherwise returns false. |
6 |
int countTokens()
It returns total number of tokens in the StringTokenizer object. |
Let's consider an example program to illustrate methods of StringTokenizer class.
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
String url = "www.btechsmartclass.com";
String title = "BTech Smart Class";
StringTokenizer tokens = new StringTokenizer(title);
StringTokenizer anotherTokens = new StringTokenizer(url, ".");
System.out.println("\nTotal tokens in title is " + tokens.countTokens());
System.out.print("Tokens in the title => ");
while(tokens.hasMoreTokens()) {
System.out.print(tokens.nextToken() + ", ");
}
System.out.println("\n\nTotal tokens in url is " + anotherTokens.countTokens());
System.out.println("Tokens in the url with delimeter (.) => ");
while(anotherTokens.hasMoreElements()) {
System.out.print(anotherTokens.nextElement() + ", ");
}
}
}
When we execute the above code, it produce the following output.