Split a string using StringTokenizer - Java @ Desk

Friday, May 17, 2013

Split a string using StringTokenizer




java.util.StringTokenizer class is used to split a String object. It require an input String along with the delimiter that needs to be used to split the string. It returns the array ob objects of length equal to split number of objects.



import java.text.ParseException;
import java.util.StringTokenizer;

public class SplitStringTokenizer {
    public static void main(String args[]) throws ParseException {
        String input = "My name is Kumar. I am from Mumbai, and I learn and implement java on my own."
                + "I love writing for my blog";

        // Apply split using "."
        StringTokenizer stringTokenizer = new StringTokenizer(input, ".");
        System.out.println("Number of tokens : " + stringTokenizer.countTokens());
        // Check for tokens
        while (stringTokenizer.hasMoreTokens()) {
            System.out.println("Current token is : " + stringTokenizer.nextToken());
        }
    }
}

Output :
Number of tokens : 3
Current token is : My name is Kumar
Current token is : I am from Mumbai, and I learn and implement java on my own
Current token is : I love writing for my blog






No comments:

Post a Comment