|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Using the StringTokenizer to Split a String
This example shows how to split a string using the StringTokenizer class. The StringTokenizer has three contructors and one of them takes the String to be split as parameter, and that is the constructor we use in this example. Since no delimiter is passed to it the default delimiters for the StringTokenizer are used: - the space character - the tab character - the newline character - the carriage-return character - and the form-feed character In this example we only use the space character. After the StringTokenizer object is constructed it is possible to check how many tokens it contains by using the countTokens() method. Do display each token we iterate through it using the hasMoreElements() method and call nextToken(). In order to use the hasMoreElements() method the StringTokenizer must implement the Iterator interface which also contains a method called nextElement(). We could as easily use that method (which is commented out below). The only difference is that it returns an Object instance as opposed to the nextToken() method which returns a String object. |
package com.javadb.examples; import java.util.StringTokenizer; /** * * @author www.javadb.com */ public class Main { public static void main(String[] args) { StringTokenizer tokenizer = new StringTokenizer("This is a StringTokenizer Java Code Example"); //Check the number of tokens that this tokenizer object contain System.out.println("Number of tokens: " + tokenizer.countTokens()); //Iterate through the tokenizer object and print out each element while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); System.out.println(token); } //Using the nextElement method: /* while (tokenizer.hasMoreElements()) { String token = tokenizer.nextElement().toString(); System.out.println("token1 = " + token); } */ } } |
| The output from the code above would be: |
This is a StringTokenizer Java Code Example |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
