Splits String into ArrayList of words separated by separator No elements will be "". e.g. - Java java.lang

Java examples for java.lang:String Split

Description

Splits String into ArrayList of words separated by separator No elements will be "". e.g.

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.Arrays;

import java.util.Iterator;

public class Main {
    /**/*  ww w.j  a v a  2 s. c o  m*/
     * Splits String into ArrayList<String> of words separated by separator<br/>
     * No elements will be "".<br/>
     * e.g. split("a b", " ") returns ArrayList<String>(Arrays.asList({"a","b"}))<br/>
     * @param str String to be split
     * @param separator String that marks splits 
     * @return This same string as ArrayList<String> split by separator
     */
    public static ArrayList<String> split(String str, String separator) {
        ArrayList<String> forReturn = new ArrayList<String>(
                Arrays.asList((str + separator).split(separator)));
        Iterator<String> iter;

        //trim elements
        iter = forReturn.iterator();
        int i = 0;
        while (iter.hasNext()) {
            forReturn.set(i, iter.next().trim());
            i++;
        }

        //remove empty elements
        iter = forReturn.iterator();
        while (iter.hasNext()) {
            String string = iter.next();
            if (string.equals("")) {
                iter.remove();
            }
        }

        return forReturn;

    }

    /**
     * Splits String into ArrayList<String> of words separated by spaces
     * No elements will be "".
     * e.g. split("a b", " ") returns ArrayList<String>(Arrays.asList({"a","b"}))
     * @param str String to be split
     * @return This same string as ArrayList<String> of words
     */
    public static ArrayList<String> split(String str) {
        return split(str, " ");
    }
}

Related Tutorials