Java String Split by Separator split(String s, String separator)

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

Description

Splits string by separator, if separator in string is backslashed, i.e.

License

Apache License

Declaration

public static List<String> split(String s, String separator) 

Method Source Code


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

import java.util.ArrayList;

import java.util.List;

public class Main {
    /** Splits string by separator, if separator in string is backslashed, i.e. prefixed by \ then
     *  it's ignored(preserved).//from ww w.  j av  a2  s.  c  o m
     **/
    public static List<String> split(String s, String separator) {
        if (s == null)
            return null;
        List<String> rslt = null;
        if (s.isEmpty() || isEmpty(separator)) {
            rslt = new ArrayList<>(1);
            rslt.add(s);
            return rslt;
        }

        //return s.split(COMMA_SPLIT); - NOT WORKING when compiled to JS

        int start = 0;
        int p = start;
        do {
            int j = s.indexOf(separator, p);
            if (j == -1) {
                if (rslt == null) {
                    rslt = new ArrayList<>(1);
                    rslt.add(s);
                    return rslt;
                }
                rslt.add(s.substring(start));
                break;
            }
            if (j > 0 && s.charAt(j - 1) == '\\') {
                p = j + 1;
                continue;
            } else {
                if (rslt == null)
                    rslt = new ArrayList<String>();
                rslt.add(s.substring(start, j));
                start = j + 1;
                p = start;
            }

        } while (true);

        return rslt;
    }

    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0; // optimize like Guava: s.isEmpty() -> s.length() == 0
    }
}

Related

  1. split(String s, char separator)
  2. split(String s, char separator)
  3. split(String s, char separator)
  4. split(String s, String separator)
  5. split(String s, String separator)
  6. split(String s, String separator)
  7. split(String src, char separator)
  8. split(String src, char separator, boolean trim)
  9. split(String str, char separator)