Splits up a string into a list of lines - Java java.lang

Java examples for java.lang:String Split

Description

Splits up a string into a list of lines

Demo Code

import java.util.Vector;

public class Main{

    public static void main(String[] argv){
        String data = "bo\nok2s\n.c\nom";
        System.out.println(lineSplit(data));
    }// www . j a v a2 s  . c  o  m
    /**
     * Splits up a string into a list of lines. It is equivalent to
     * <tt>split(data, '\n')</tt>.
     *
     * @param data
     *            the string to split up into lines.
     * @return the list of lines available in the string.
     */
    public static Vector<String> lineSplit(String data) {
        return split(data, '\n');
    }
    /**
     * Splits up a string where elements are separated by a specific character
     * and return all elements.
     *
     * @param data
     *            the string to split up.
     * @param ch
     *            the separator character.
     * @return the list of elements.
     */
    public static Vector<String> split(String data, int ch) {
        Vector<String> elems = new Vector<String>();
        int pos = -1;
        int i = 0;
        while ((pos = data.indexOf(ch, i)) != -1) {
            String elem = data.substring(i, pos);
            elems.addElement(elem);
            i = pos + 1;
        }
        elems.addElement(data.substring(i));
        return elems;
    }

}

Related Tutorials