In this article, you will learn the difference between StringTokenizer and split() method in Java.
Let’s see how these two methods are used to split a given string then we will discuss the difference.
StringTokenizer
import java.util.*; class JavaExample { public static void main(String[] args) { String str = "20-09-2022"; StringTokenizer strToken = new StringTokenizer(str, "-"); // The returns the number of possible substrings after split System.out.println("Number of Substrings after split: " + strToken.countTokens()); // printing the substrings after split for (int i = 0; strToken.hasMoreTokens(); i++) System.out.println((i+1)+": "+ strToken.nextToken()); } }
Output:
StringTokenizer(String str, String delimiter, boolean flag): You can also pass a boolean flag (true or false) while calling the StringTokenizer constructor.
Example 1: If the flag is false
Input : Given string is “Welcome readers” and delimiter is ” ”
code: StringTokenizer strToken = new StringTokenizer(str, " ", false);
Output: tokens are “Welcome” and “readers”. //two substrings
Example 2: If the flag is true
Input : Given string is “Welcome readers” and delimiter is ” ”
code: StringTokenizer strToken = new StringTokenizer(str, " ", true);
Output: tokens are “Welcome”, ” ” and “readers”. //three substrings
String split() Method
The split() method belongs to the java string class. This method is also used to split the method based on the provided delimiter.
class JavaExample { public static void main(String[] args) { String str = "Welcome to BeginnersBook"; //delimiter is whitespace " " here String[] subStr = str.split(" "); System.out.println("Substrings after split: "+subStr.length); for (int i = 0; i < subStr.length; i++) System.out.println((i+1)+": " + subStr[i]); } }
Output:
StringTokenizer vs Split Method – Which is better?
The split() method is the better than StringTokenizer, because it is more robust and easier to use. It is slower than StringTokenizer, however the StringTokenizer is legacy class so split() method is preferred method for string splitting.
Difference between StringTokenizer and split() method
StringTokenizer | split() method |
---|---|
It is a class. | It is a method of String class. |
It returns a single substring at a time. The next substring is read using nextToken() method of this class. | It returns an array of substrings. The substrings can be traversed just like a normal string array elements. |
Syntax is complex. | Syntax is easier. |
StringTokenizer only accepts the string delimiter. | The split() method can accept string delimiter and regular expressions. |
It is faster because it doesn’t allow regular expression. | It is comparatively slower but has more uses. |
Substrings often referred as tokens are generated using the constructor of this class. | It doesn’t have any constructors as it is not a class, rather a method. |
Less Robust. | More Robust. |