Splits up a string where elements are separated by a specific character and return all elements. - Java java.lang

Java examples for java.lang:String Split

Description

Splits up a string where elements are separated by a specific character and return all elements.

Demo Code

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Vector;

public class Main{

    public static void main(String[] argv){
        String data = "java2s.com";
        int ch = .;
        System.out.println(split(data,ch));
    }//from   w  ww  .j av  a2s.  c  om
    /**
     * 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