StringTokenizer Class in the java.util Package
Overview
The StringTokenizer class splits the string of a String object into multiple token strings using a specific delimiter. The delimiter can be a special character, a space, a single character, or a string containing multiple characters. Because the StringTokenizer class uses the Enumeration interface, the split strings exist in enumerable form.
StringTokenizer Constructors
| Constructor | Description |
|---|---|
| StringTokenizer(String str) | Default constructor. |
| StringTokenizer(String str, String delim) | Constructor that receives the delimiter as an argument. |
| StringTokenizer(String str, String delim, boolean returnDelims) | Constructor that receives the delimiter and whether to return delimiters as arguments. |
StringTokenizer Methods
| Method | Description |
|---|---|
| int countTokens() | Returns the number of split tokens. |
| boolean hasMoreElements() | Returns true if there is another element to return; otherwise returns false. Same as hasMoreTokens(). |
| boolean hasMoreTokens() | Returns true if there is another token to return; otherwise returns false. |
| Object nextElement() | Returns the next token. It returns Object, but the actual value is a String. |
| String nextToken() | Returns the next token. The previous token is removed. |
| String nextToken(String delim) | Changes the delimiter and then returns the next token. |
StringTokenizer Examples
Example 1)
package com.devkuma.tutorial.java.util;
import java.util.StringTokenizer;
public class StringTokenizerClass {
public static void main(String[] args) {
String str = "java,c,c++,c#,scala,xml,javascript";
StringTokenizer st = new StringTokenizer(str, ",");
while (st.hasMoreTokens()) {
String lang = st.nextToken();
System.out.println(lang);
}
}
}
Execution result:
java
c
c++
c#
scala
xml
javascript
Example 2)
package com.devkuma.tutorial.javautil;
import java.util.StringTokenizer;
public class StringTokenizerClass2 {
public static void main(String[] args) {
String str = "java,c,c++,c#,scala,xml,javascript";
StringTokenizer st = new StringTokenizer(str, ",", true);
while (st.hasMoreTokens()) {
String lang = st.nextToken();
System.out.println(lang);
}
}
}
Execution result:
java
,
c
,
c++
,
c#
,
scala
,
xml
,
javascript