Introduction
Big Hello! In this tutorial we will learn how to use StringTokenizer in Java. As the name suggests it breaks down string into smaller sub parts or tokens.
Just like complex problems are broken into smaller subproblems, StringTokenizer breaks strings into smaller tokens. This can be useful in many usecases
It can be useful in below usecases:
UseCases
- Tokenizing user inputs
- URL Parsing
- Data transformation
- Parsing configuration files
- Parsing CSV files
Usage
Let us see how we can use StringTokenizer in Java
Step 1:
First we need to import the class
|
|
Step 2:
We can create StringTokenizer by passing it 2 arguments. First argument is the string we want to tokenize. Second argument is the token by which string should be divided.
After initializing the tokenizer, we can get token by using a while loop.
“stringTokenizer.hasMoreTokens()” checks if there are more tokens available from this tokenizer’s string.
If this method returns true, then a subsequent call to “nextToken” with no argument will successfully return a token as shown in below code.
|
|
|
|
Basic tokenization
Counting tokens
We can count no of tokens available in the string using countTokens() method
|
|
|
|
Multiple Delimiters
Instead of 1 delimiter we can specify multiple delimiters as shown in below example.
|
|
|
|
Returning delimiters as tokens
By default StringTokenizer does not return delimiters as tokens. You can change this by using adding 3rd argument to StringTokenizer instance as true
|
|
|
|
Limitations in StringTokenizer
StringTokenizer do not support regular expressions which is required for complex parsing. It can be used only for simple tokenization tasks.
Conclusion
In this tutorial we learnt how to use StringTokenizer class with practical examples.