How do I split a string?

Prior to Java 1.4 we use StringTokenizer to split a tokenized string, for example a comma separated string. In Java 1.4 or later the String class introduce a String.split(String regex) method that simplify this process.

Below is a code sample how to do it.

package org.kodejava.example.lang;

import java.util.Arrays;

public class StringSplit {
    public static void main(String[] args) {
        String data = "1,Diego Maradona,Footballer,Argentina";
        String[] items = data.split(",");

        // Iterates the array to print it out.
        for (String item : items) {
            System.out.println("item = " + item);

        // Or simply use Arrays.toString() when print it out.
        System.out.println("item = " + Arrays.toString(items));

The result of the code snippet:

item = 1
item = Diego Maradona
item = Footballer
item = Argentina
item = [1, Diego Maradona, Footballer, Argentina]