Java String Split by Delimiter split(String s, String delimiter)

Here you can find the source of split(String s, String delimiter)

Description

split

License

Apache License

Declaration

public static String[] split(String s, String delimiter) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    public static String[] split(String s, String delimiter) {
        //Can't use StringTokenizer because it skips blank fields.
        //Can't use it with returnTokens because it screws up multi-char delimiters.
        //All in all, it's a pretty goddamn useless utility
        if (s.endsWith(delimiter)) {
            s += delimiter;/*  w  w w  . j a v a2s .com*/
        }
        ArrayList<String> al = new ArrayList<String>();
        int p1 = 0, p2 = 0;
        String prev = delimiter;
        while ((p2 = s.indexOf(delimiter, p1)) != -1) {
            String fld = s.substring(p1, p2);
            if (fld.equals(delimiter) && prev.equals(delimiter)) {
                al.add("");
            } else if (!fld.equals(delimiter)) {
                al.add(fld);
            }
            prev = fld;
            p1 = p2 + delimiter.length();
        }
        if (p1 != s.length())
            al.add(s.substring(p1));
        //String rtn[] = (String[])al.toArray(new String[0]);
        //Since above line doesn't work with .NET we have to do it this way:
        String rtn[] = new String[al.size()];
        int i = 0;
        Iterator<String> iter = al.iterator();
        while (iter.hasNext()) {
            rtn[i++] = (String) iter.next();
        }
        return rtn;
    }
}

Related

  1. split(String s, char delimiter)
  2. split(String s, String delim)
  3. split(String s, String delim)
  4. split(String s, String delim)
  5. split(String s, String delimiter)
  6. split(String s, String delimiter)
  7. split(String src, char delim)
  8. split(String src, char delim)
  9. split(String src, String delimiter)