The code below is an example of using StringTokenizer
to split a string. In the current JDK this class is discouraged to be used, use the String.split(...)
method instead or using the new java.util.regex
package.
package org.kodejava.example.util;
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
StringTokenizer st =
new StringTokenizer("A StringTokenizer sample");
// get how many tokens inside st object
System.out.println("Tokens count: " + st.countTokens());
// iterate st object to get more tokens from it
while (st.hasMoreElements()) {
String token = st.nextElement().toString();
System.out.println("Token = " + token);
}
// split a date string using a forward slash as delimiter
st = new StringTokenizer("2017/08/20", "/");
while (st.hasMoreElements()) {
String token = st.nextToken();
System.out.println("Token = " + token);
}
}
}
Here is the result of this sample code:
Tokens count: 3
Token = A
Token = StringTokenizer
Token = sample
Token = 2017
Token = 08
Token = 20
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019