Java - Write code to split - splits string using space delimited

Requirements

Write code to split - splits string using space delimited

Demo

//package com.book2s;
import java.util.*;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        System.out.println(java.util.Arrays.toString(split(str)));
    }//from   w w  w  .j  a  v  a  2 s.  c o  m

    /**
     * split - splits string using space delimited 
     * @param str - string to split
     * @return array of strings
     */
    public static String[] split(String str) {
        if (str == null)
            return null;
        return split(str, null);
    }

    /**
     * split - splits string using given delimiter
     * @param str - string to split
     * @param delim - string delimiter
     * @return array of strings
     */
    public static String[] split(String str, String delim) {
        if (str == null)
            return null;
        str = str.trim();
        if (str.length() == 0)
            return new String[0];
        List list = new ArrayList();
        StringTokenizer st = null;
        if (delim == null)
            st = new StringTokenizer(str);
        else
            st = new StringTokenizer(str, delim);
        while (st.hasMoreTokens()) {
            list.add(st.nextToken());
        }
        return (String[]) list.toArray(new String[list.size()]);
    }
}

Related Exercise