StringTokenizer Class in Java
StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. It provides the first step in the parsing process often called lexer or scanner. The String Tokenizer class allows an application to break strings into tokens. It implements the Enumeration interface. This class is used for parsing data. To use String Tokenizer class we have to specify an input string and a string that contains delimiters. Delimiters are the characters that separate tokens. Each character in the delimiter string is considered a valid delimiter. Default delimiters are whitespaces, new line, space, and tab.
Constructors of StringToken: Let us consider ‘str’ as the string to be tokenized
- StringTokenizer(String str): default delimiters like newline, space, tab, carriage return, and form feed.
- StringTokenizer(String str, String delim): delim is a set of delimiters that are used to tokenize the given string.
- StringTokenizer(String str, String delim, boolean flag): The first two parameters have the same meaning wherein The flag serves the following purpose.
3.1: If the flag is false, delimiter characters serve to separate tokens
Input : if string --> "hello geeks" and Delimiter is " ", then Output: tokens are "hello" and "geeks".
3.2: If the flag is true, delimiter characters are considered to be tokens.
Input : String --> is "hello geeks"and Delimiter is " ", then Output: Tokens --> "hello", " " and "geeks".
Methods Of StringTokenizer Class
|countTokens()||Returns the total number of tokens present|
|hasMoreToken()||Tests if tokens are present for the StringTokenizer’s string|
|nextElement()||Returns an Object rather than String|
|hasMoreElements()||Returns the same value as hasMoreToken|
|nextToken()||Returns the next token from the given StringTokenizer.|
Using Constructor 1 - Hello Geeks How are you Using Constructor 2 - JAVA Code String Using Constructor 3 - JAVA : Code : String
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.