How do I split a string?

Prior to Java 1.4 we use java.util.StringTokenizer class to split a tokenized string, for example a comma separated string. Starting from Java 1.4 and later the java.lang.String class introduce a String.split(String regex) method that simplify this process.

Below is a code snippet how to do it.

package org.kodejava.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]
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.