StringTokenizer
The Java StringTokenizer class helps you break strings into small pieces. This is helpful if
you have a bunch of data stored in a string, separated by commas or spaces. First, you need to
import the java.util library:
import java.util.*;Then, you need to create a new StringTokenizer:
StringTokenizer st = new StringTokenizer(fullString, delimeters);Here, fullString is the string you want to break into pieces, and delimeters is a string
that contains all the characters that separate the pieces in fullString. For example, if you
had a list of names that were separated by commas and spaces, then delimeters would be
" ,". Here’s an example:
String fullString = "Bob, Joe, Lisa, Katie";
StringTokenizer st = new StringTokenizer(fullString, " ,");Now, you need to break apart the pieces. You can check if you’ve stepped through all of them
by calling the hasMoreTokens() method, which will return true when you’ve read the entire
string. You can get the NEXT piece of the string by calling the nextToken() method. Here’s
an example that prints all the names in fullString:
while (st.hasMoreTokens())
{
String name = st.nextToken();
System.out.println(name);
}This will print:
Bob
Joe
Lisa
Katie