java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.sample.java.lang;

public class StringSplit
{
    public static void main(String[] args)
    {
        String data = "1,Diego Maradona,Footballer,Argentina";
        String[] items = data.split(",");
        for (String item : items)
        {
            System.out.println("item = " + item);
        }
    }
}