Java - Write code to Parse a comma-delimited string into a string array.

Requirements

Write code to Parse a comma-delimited string into a string array.

Demo

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

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

    /**
     * Parse a comma-delimited string into a string array.
     */
    public static String[] parseCommaDelimited(String delimited) {
        ArrayList<String> list;
        int pos;
        StringBuffer buf;
        String item;

        list = new ArrayList<String>();
        buf = new StringBuffer(delimited);
        while (buf.length() > 0) {
            for (pos = 0; pos < buf.length(); pos++) {
                if (buf.charAt(pos) == ',')
                    break;
            }
            item = buf.substring(0, pos);
            list.add(item);
            buf = buf.delete(0, pos + 1);
        }

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

Related Exercise