Java - Write code to Split the string into an array, using the separator.

Requirements

Write code to Split the string into an array, using the separator.

Demo

import java.lang.reflect.Array;

public class Main{
    public static void main(String[] argv){
        String s = "book2s.com";
        String separator = "book2s.com";
        System.out.println(java.util.Arrays.toString(split(s,separator)));
    }//from   ww w .j a v a  2  s.  c  o  m
    /**
     * Splits the string into an array, using the separator. If separator is
     * not found in the string, the whole string is returned in the array.
     *
     * @param s the string
     * @param separator the separator
     * @return array of strings
     */
    public static String[] split(String s, String separator) {

        HsqlArrayList list = new HsqlArrayList();
        int currindex = 0;

        for (boolean more = true; more;) {
            int nextindex = s.indexOf(separator, currindex);

            if (nextindex == -1) {
                nextindex = s.length();
                more = false;
            }

            list.add(s.substring(currindex, nextindex));

            currindex = nextindex + separator.length();
        }

        return (String[]) list.toArray(new String[list.size()]);
    }
}

Related Exercise