Java - Write code to split a string by a char

Requirements

Write code to split a string by a char

Demo

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

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        char separatorChar = 'o';
        System.out.println(java.util.Arrays.toString(split(str,
                separatorChar)));/* www .j ava  2  s  . co m*/
    }

    public static String[] split(String str, char separatorChar) {
        if (str == null) {
            return null;
        }

        int length = str.length();

        if (length == 0) {
            return new String[0];
        }

        List<String> list = new ArrayList<String>();
        int i = 0;
        int start = 0;

        while (i < length) {
            if (str.charAt(i) == separatorChar) {
                list.add(str.substring(start, i));

                start = ++i;
                continue;
            }
            i++;
        }

        list.add(str.substring(start, i));

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

Related Exercise