Java StringTokenizer – Multiple delimiters example shows how to specify multiple delimiters while tokenizing the string content using the StringTokenizer class.
How to specify multiple delimiters in StringTokenizer?
When we create a StringTokenizer object using the below given single arguemnt constructor, it uses the default set of delimiters.
1 |
public StringTokenizer(String str) |
The default delimiters are a space character, a tab character, a new line character, a carriage return character, and the form feed character. The string will be tokenized according to these characters.
When we use the below given two-argument constructor, we can specify the string content as well as the delimiter we want to use to tokenize the string content.
1 |
public StringTokenizer(String string, String delimiter) |
Using this constructor we can specify the delimiter we want to use. See below example that tokenizes the string using a comma.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.javacodeexamples.stringtokenizerexamples; import java.util.StringTokenizer; public class StringTokenizerMultipleTokens { public static void main(String[] args) { String string = "one,two,three"; StringTokenizer st = new StringTokenizer(string, ","); while(st.hasMoreTokens()) { System.out.println( st.nextToken() ); } } } |
Output
1 2 3 |
one two three |
For any particular use case, if you want to tokenize the string content using more than one or multiple delimiters, you can do so using the same constructor. In this case, when you create the StringTokenizer object, pass all the delimiters you want to use as a single string for the delimiter argument.
For example, if you want to tokenize the string content using a comma, a dot, a hyphen, and a pipe, you can pass “,.-|” as delimiter value. The specified string will then be tokenized based on the multiple delimiters you have provided.
Please see the below example that uses the delimiters we just discussed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.javacodeexamples.stringtokenizerexamples; import java.util.StringTokenizer; public class StringTokenizerMultipleTokens { public static void main(String[] args) { String string = "Java,StringTokenizer-multiple|delimiters"; StringTokenizer st = new StringTokenizer(string, ",.-|"); while(st.hasMoreTokens()) { System.out.println( st.nextToken() ); } } } |
Output
1 2 3 4 |
Java StringTokenizer multiple delimiters |
As you can see from the output, all the delimiters we specified in the constructor were used to generate the string tokens.
If you want to learn more about the tokenizer, please visit the Java StringTokenizer Tutorial.
Please let me know your views in the comments section below.