Java String Split by Delimiter splitString(String str, String delim)

Here you can find the source of splitString(String str, String delim)

Description

split String

License

Open Source License

Declaration

static public String[] splitString(String str, String delim) 

Method Source Code

//package com.java2s;
// This copy of Ice is licensed to you under the terms described in the

public class Main {
    static public String[] splitString(String str, String delim) {
        java.util.List<String> l = new java.util.ArrayList<>();
        char[] arr = new char[str.length()];
        int pos = 0;

        int n = 0;
        char quoteChar = '\0';
        while (pos < str.length()) {
            if (quoteChar == '\0' && (str.charAt(pos) == '"' || str.charAt(pos) == '\'')) {
                quoteChar = str.charAt(pos++);
                continue; // Skip the quote.
            } else if (quoteChar == '\0' && str.charAt(pos) == '\\' && pos + 1 < str.length()
                    && (str.charAt(pos + 1) == '"' || str.charAt(pos + 1) == '\'')) {
                ++pos; // Skip the backslash
            } else if (quoteChar != '\0' && str.charAt(pos) == '\\' && pos + 1 < str.length()
                    && str.charAt(pos + 1) == quoteChar) {
                ++pos; // Skip the backslash
            } else if (quoteChar != '\0' && str.charAt(pos) == quoteChar) {
                ++pos;/*from   w w w  . j  a va 2s . c o m*/
                quoteChar = '\0';
                continue; // Skip the quote.
            } else if (delim.indexOf(str.charAt(pos)) != -1) {
                if (quoteChar == '\0') {
                    ++pos;
                    if (n > 0) {
                        l.add(new String(arr, 0, n));
                        n = 0;
                    }
                    continue;
                }
            }

            if (pos < str.length()) {
                arr[n++] = str.charAt(pos++);
            }
        }

        if (n > 0) {
            l.add(new String(arr, 0, n));
        }
        if (quoteChar != '\0') {
            return null; // Unmatched quote.
        }
        return l.toArray(new String[0]);
    }
}

Related

  1. splitString(String data, String delimiter)
  2. splitString(String originalString, String delimeter)
  3. splitString(String source, String delimiter)
  4. splitString(String splitStr, String delim)
  5. splitString(String str, char delim)
  6. splitString(String str, String delimiter)
  7. splitString(String str, String delims)
  8. splitString(String toSplit, String delimiter)
  9. splitStringList(String strList, String delimit)