Java - Write code to split a string by substring method and for loop

Requirements

Write code to split a string by substring method and for loop

Demo

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

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        String s = "book2s.com";
        char separator = 'a';
        System.out.println(split(s, separator));
    }/*from w ww  .ja va 2s  .co m*/

    public static List<String> split(String s, char separator) {
        int i = s.indexOf(separator);
        List<String> list = new ArrayList<>();
        if (i < 0) {
            list.add(s);
            return list;
        }
        for (; i >= 0 && i < s.length();) {
            String sub = s.substring(0, i).trim();
            if (!sub.isEmpty()) {
                list.add(sub);
            }
            s = s.substring(i + 1).trim();
            i = s.indexOf(separator);
            if (i < 0) {
                if (!s.isEmpty()) {
                    list.add(s);
                }
                break;
            }
        }
        return list;
    }
}

Related Example