StringTokenizer in JavaThe java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a String. It is a legacy class of Java. It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter. In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens. Constructors of the StringTokenizer ClassThere are 3 constructors defined in the StringTokenizer class.
Methods of the StringTokenizer ClassThe six useful methods of the StringTokenizer class are as follows:
Example of StringTokenizer ClassLet's see an example of the StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace. Simple.java Output: my name is khan The above Java code, demonstrates the use of StringTokenizer class and its methods hasMoreTokens() and nextToken(). Example of nextToken(String delim) method of the StringTokenizer classTest.java Output: Next token is : my Note: The StringTokenizer class is deprecated now. It is recommended to use the split() method of the String class or the Pattern class that belongs to the java.util.regex package.Example of hasMoreTokens() method of the StringTokenizer classThis method returns true if more tokens are available in the tokenizer String otherwise returns false. StringTokenizer1.java Output: Demonstrating methods from StringTokenizer class The above Java program shows the use of two methods hasMoreTokens() and nextToken() of StringTokenizer class. Example of hasMoreElements() method of the StringTokenizer classThis method returns the same value as hasMoreTokens() method of StringTokenizer class. The only difference is this class can implement the Enumeration interface. StringTokenizer2.java Output: Hello everyone I am a Java developer The above code demonstrates the use of hasMoreElements() method. Example of nextElement() method of the StringTokenizer classnextElement() returns the next token object in the tokenizer String. It can implement Enumeration interface. StringTokenizer3.java Output: Hello Everyone Have a nice day The above code demonstrates the use of nextElement() method. Example of countTokens() method of the StringTokenizer classThis method calculates the number of tokens present in the tokenizer String. StringTokenizer4.java Output: Total number of Tokens: 6 The above Java code demonstrates the countTokens() method of StringTokenizer() class. Next TopicJava String FAQs |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India