Like the split function on String, but does not require the delimiter to be a regular expression (this does not matter much, except when dynamically loading the delim that may have regular expression special chars in it). - Java java.lang

Java examples for java.lang:String Split

Description

Like the split function on String, but does not require the delimiter to be a regular expression (this does not matter much, except when dynamically loading the delim that may have regular expression special chars in it).

Demo Code

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

public class Main {
    public static void main(String[] argv) {
        String data = "java2s.com";
        String delim = "java2s.com";
        System.out.println(java.util.Arrays.toString(explode(data, delim)));
    }/*from w w w .  j av a  2s  . c  o m*/

    /**
     * Operates a lot like the split function on String, but does not require the delimiter to be
     * a regular expression (this does not matter much, except when dynamically loading the delim
     * that may have regular expression special chars in it).
     * @param data the data to split
     * @param delim the delimiting string to use
     * @return an array of strings, without the delimiter
     */
    public static String[] explode(String data, String delim) {
        ArrayList<String> list = new ArrayList<String>();
        StringBuffer sb = new StringBuffer(data);
        boolean splitting = true;
        int curpos = 0;
        int delimpos = sb.indexOf(delim);
        while (splitting) {
            if (delimpos >= 0) {
                list.add(sb.substring(curpos, delimpos));
            } else {
                list.add(sb.substring(curpos));
                splitting = false;
            }
            curpos = delimpos + delim.length();
            delimpos = sb.indexOf(delim, curpos);
        }

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

Related Tutorials