Java - Write code to Convert a string that has delimited values (say comma delimited) in a String[].

Requirements

Write code to Convert a string that has delimited values (say comma delimited) in a String[].

Demo

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

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

    /**
     * Convert a string that has delimited values (say comma delimited) in a
     * String[]. You must explicitly choose whether or not to include empty
     * values (say two commas that a right beside each other.
     * 
     * <P>
     * e.g. "alpha,beta,,theta"<br>
     * With keepEmpties true, this results in a String[] of size 4 with the
     * third one having a String of 0 length. With keepEmpties false, this
     * results in a String[] of size 3.
     * </P>
     * <P>
     * </P>
     * <P>
     * e.g. ",alpha,beta,,theta,"<br>
     * With keepEmpties true, this results in a String[] of size 6 with the
     * 1st,4th and 6th one having a String of 0 length. With keepEmpties false,
     * this results in a String[] of size 3.
     * </P>
     */
    public static String[] delimitedToArray(String str, String delimiter,
            boolean keepEmpties) {

        ArrayList<String> list = new ArrayList<String>();
        int startPos = 0;
        delimiter(str, delimiter, keepEmpties, startPos, list);
        String[] result = new String[list.size()];
        return (String[]) list.toArray(result);
    }

    private static void delimiter(String str, String delimiter,
            boolean keepEmpties, int startPos, ArrayList<String> list) {

        int endPos = str.indexOf(delimiter, startPos);
        if (endPos == -1) {
            if (startPos <= str.length()) {
                String lastValue = str.substring(startPos, str.length());
                // dp("lastValue="+lastValue);
                if (!keepEmpties && lastValue.length() == 0) {
                    // dp("not keeping...");
                } else {
                    list.add(lastValue);
                }
            }
            // we have finished parsing the string...
            return;
        } else {
            // get the delimited value... add it..
            String value = str.substring(startPos, endPos);
            // dp(startPos+","+endPos+" value="+value);
            if (!keepEmpties && value.length() == 0) {
                // dp("not keeping...");
            } else {
                list.add(value);
            }
            // recursively search as we are not at the end yet...
            delimiter(str, delimiter, keepEmpties, endPos + 1, list);
        }
    }
}

Related Exercise