Java - Write code to split a string by a delimiter


Write code to split a string by a delimiter


//package com.book2s;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] argv) {
        String str = "";
        String delim = "";
        System.out.println(java.util.Arrays.toString(split(str, delim)));
    }/*from ww  w . j  a  v  a2  s . c om*/

    public static final String[] EMPTY_STRINGS = new String[0];

    public static String[] split(final String str, final String delim) {
        if (isEmpty(str)) {
            return EMPTY_STRINGS;
        final List<Object> list = new ArrayList<Object>();
        final StringTokenizer st = new StringTokenizer(str, delim);
        while (st.hasMoreElements()) {
        return (String[]) list.toArray(new String[list.size()]);

    public static final boolean isEmpty(final String text) {
        return text == null || text.length() == 0;

Related Exercise