Java - Write code to split string using given delimiter if even if token is empty.

Requirements

Write code to split string using given delimiter if even if token is empty.

Demo

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

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        String delim = "book2s.com";
        System.out.println(java.util.Arrays.toString(fsplit(str, delim)));
    }/*from   w  w w  .  ja  va  2  s.  co m*/

    /**
     * fsplit - splits string using given delimiter if even if token is empty.
     * @param str - string to split
     * @param delim - string delimiter
     * @return array of strings
     */
    public static String[] fsplit(String str, String delim) {
        if (str == null)
            return null;
        str = str.trim();
        if (str.length() == 0)
            return new String[0];
        List list = new ArrayList();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            boolean isDelim = false;
            for (int j = 0; j < delim.length(); j++) {
                if (str.charAt(i) == delim.charAt(j)) {
                    isDelim = true;
                    break;
                }
            }
            if (isDelim) {
                list.add(sb.toString());
                sb.setLength(0);
            } else {
                sb.append(str.charAt(i));
            }
        }
        list.add(sb.toString());
        return (String[]) list.toArray(new String[list.size()]);
    }
}