next up previous
Next: Exercises Up: Unit 06 Previous: The class EncryptedText: example

The class StringTokenizer

The class StringTokenizer allows us to divide a string into tokens. A token is the maximal sequence of consecutive characters of a string that are not delimiters. The default delimiters are " \t\n\r\f", i.e., the space character, the tab character, the newline character, the return character, and the form-feed character.

Example: The tokens of the string:

"I am   a
  student
of Introduction     to Programming"
are: "I", "am", "a", "student", "of", "Introduction", "to", "Programming".

An object of type StringTokenizer is constructed starting from a string to be tokenized, and internally maintains a current position within the string. The class exports some methods that allow us to advance this position, and to return the token as a substring of the string used to create the StringTokenizer object.

The StringTokenizer class has the following constructors (among others):

The StringTokenizer class has the following methods (among others):

Example: Use of an object of type StringTokenizer. The following fragment of code

StringTokenizer st = new StringTokenizer("I am   a   \n  student");
while (st.hasMoreTokens()) {
  System.out.println(st.nextToken());
}
prints the following output:
I
am
a
student

Notes:


next up previous
Next: Exercises Up: Unit 06 Previous: The class EncryptedText: example