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

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

Description

split

License

Apache License

Declaration

public static String[] split(String str, String separator) 

Method Source Code

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

import java.util.ArrayList;
import java.util.List;

public class Main {
    private static final String[] EMPTY_STRING_ARRAY = new String[0];

    public static String[] split(String str, String separator) {
        if (str == null) {
            return null;
        }//from www .j  ava  2s.c o  m
        if (separator == null || separator.length() != 1) {
            return null;
        }
        int len = str.length();
        if (len == 0) {
            return EMPTY_STRING_ARRAY;
        }
        List<String> list = new ArrayList<String>();
        int sizePlus1 = 1;
        int i = 0, start = 0;
        boolean match = false;
        // Optimise 1 character case
        char sep = separator.charAt(0);
        while (i < len) {
            if (str.charAt(i) == sep) {
                if (match) {
                    if (sizePlus1++ == 0) {
                        i = len;
                    }
                    list.add(str.substring(start, i));
                    match = false;
                }
                start = ++i;
                continue;
            }
            match = true;
            i++;
        }
        if (match) {
            list.add(str.substring(start, i));
        }
        return list.toArray(new String[list.size()]);
    }
}

Related

  1. split(String str, char separatorChar)
  2. split(String str, char separatorChar)
  3. split(String str, char separatorChar)
  4. split(String str, char separatorChar)
  5. split(String str, char separatorChar, boolean preserveAllTokens)
  6. split(String str, String separator)
  7. split(String str, String separator, boolean preserveEmptyToken)
  8. split(String string, char separator)
  9. split(String strToSplit, String strSeparator, int iLimit)