In this quick article, we’ll explore a fundamental class in Java – the StringTokenizer.
2. StringTokenizer
The StringTokenizer class helps us split Strings into multiple tokens.
StreamTokenizer provides similar functionality but the tokenization method of StringTokenizer is much simpler than the one used by the StreamTokenizer class. Methods of StringTokenizer do not distinguish among identifiers, numbers, and quoted strings, nor recognize and skip comments.
The set of delimiters (the characters that separate tokens) may be specified either at the creation time or on a per-token basis.
3. Using the StringTokenizer
The simplest example of using StringTokenizer will be to split a String based on specified delimiters.
In this quick example, we’re going to split the argument String and add the tokens into a list*:*
public List<String> getTokens(String str) {
List<String> tokens = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(str, ",");
while (tokenizer.hasMoreElements()) {
tokens.add(tokenizer.nextToken());
}
return tokens;
}
Notice how we’re breaking the String into the list of tokens based on delimiter ‘*,*‘. Then in the loop, using tokens.add() method; we are adding each token into the ArrayList.
For example, if a user gives input as “Welcome,to,baeldung.com“, this method should return a list containing a three-word fragment as “Welcome“, “to” and “baeldung.com“.