StringTokenizer class, from where we can split a string into tokens. In this example we are going to show the use of
StringTokenizer class, as well as some of its basic operations.
1. Syntax of the constructors
Depending on our application, we can choose one of the below constructors for
StringTokenizer(String str, String delim)
StringTokenizer(String str, String delim, boolean returnDelims)
The possible arguments that are used are:
str: is the string we want to split into tokens
delim: the defined delimiter of token separation (space is the default one)
returnDelims: declares whether to include the delimiter as a returned token (true value) or skip the delimiter (false value)
2. Example of StringTokenizer in Java
Create a new java file with the name
StringTokenizerClass and paste the following code.
As you can see in the code above, we create two instances of
StringTokenizer. In the first one we define the default delimiter, while in the second one we choose another string delimiter. In order to return all the tokens, we use a while loop where
hasMoreElements() method is called which indicates whether there are available tokens. In addition, two operations exist (
nextElement()) in order to return the value of the token. The difference between them is that
nextElement() method returns an
Object and not a
countTokens() function returns the number of the tokens each time.
Now you can see the output of the execution. As you can notice, there are the same tokens for both strings. This is happening because
StringTokenizer ignores empty elements and also we utilized the delimiter to separate tokens in both instances.
3. Download the source code
This was an example of stringtokenizer in Java.
Download the source code of this example: Java StringTokenizer Example