StringTokenizer class
The StringTokenizer class allows us to break a string into tokens. The StringTokenizer method does not distinguish among the identifiers quoted string, numbers, skip comment; and the StringTokenizer class implements the Enumeration interfaceTo use a StringTokenizer that you specify in an input String which contains delimiters.
Delimiters are nothing but only characters that separate tokens, for example, comma (,) colon(:) semicolon(;). The default delimiters are the whitespace characters space, tab, newline, and carriage return.
To read about Strings in Java pls
click
Constructor of StringTokenizer class
1. StringTokenizer(String object):
Constructs a string tokenizer for the specified string. It takes a default delimiter.
2. StringTokenizer(String object, String delimiters):
In this constructor, you can pass a delimiter according to need int form of string as a second argument.
3. StringTokenizer(String object, String delimiters, boolean deliasktoken):
This constructor has the same arguments except a boolean deliasktoken is an extra argument; this argument means if it's True then the delimiter character is also returned with the token.
Methods of the StringTokenizer class
1. int countTokens():
Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.
2. boolean hasMoreTokens():
Tests if there are more tokens available from this tokenizer's string.
3. boolean hasMoreElements()
Returns the same value as the hasMoreTokens method.
4. String nextToken():
Returns the next token from this string tokenizer.
5. Object nextElement():
Returns the same value as the nextToken method, except that its declared return value is an Object rather than a String.
6. String nextToken(String delim):
Returns the next token in this string tokenizer's string.
Program
- import java .io.*;
- import java.util.*;
- class MyStringTokenizer
- {
- public static void main(String arg[])throws IOException
- {
- String s="this ,is, the, example, of, StirgTokenizer";
-
- StringTokenizer st=new StringTokenizer(s,",");
-
- while(st.hasMoreTokens())
- {
- System.out.println(st.nextToken());
- }
- }
- }
Output
Summary
The StringTokenizer class helps to break a string object into tokens as determined by the delimiter passed into the parameter, which works as a separator you can make your own delimiter and if you do not specify a delimiter then it uses default delimiters.