Split a String


Often you need to split a String up in elements, for example if you're reading from a comma separated file.
This example shows a method that does the job in two different ways. If your delimiter is not an advanced one it's easy to make use of the split() method in the String class.
It does take a regular expression as argument, but if you have as in this example a comma as delimiter, it's no different from the argument type being a String.
The split method returns an array of Strings with which we then can loop through the elements.

The other way of splitting a String is by using the StringTokenizer.
It takes a String and a delimiter String as argument and then we can loop through it for as long as the hasMoreTokens method returns true.


import java.util.StringTokenizer;

/**
 *
 * @author javadb.com
 */

public class Main {
    
    /**
     * This method counts the number of letters in a String
     */

    public void splitString(String str) {
        
        if (str == null)
            return;
        
        //** Using the split method
        String[] elements = str.split(",");

        for (int i = 0; i < elements.length; i++)
            System.out.println(elements[i]);
        
        //** print blank row
        System.out.println();
        
        
        //** Using the StringTokenizer class
        StringTokenizer tokenizer = new StringTokenizer(str, ",");
        while (tokenizer.hasMoreTokens())
            System.out.println(tokenizer.nextToken());
    }

    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().splitString("one,two,three,four,five");
    }
}


Both ways will result in the same output:

one
two
three
four
five

one
two
three
four
five





   What kind of Java example would you like to see on this site?

   
     E-mail (optional)