Java String Split by Delimiter splitText(String text, String delimiter)

Here you can find the source of splitText(String text, String delimiter)

Description

Splits the specified text by the specified delimiter.

License

BSD License

Parameter

Parameter Description
text the target

Return

the result array.

Declaration

static String[] splitText(String text, String delimiter) 

Method Source Code


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

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

public class Main {
    /**// w ww .java2 s.  c om
     * Splits the specified text by the specified delimiter.
     * If a delimiter character appears btween double quotations,
     * this method regard it as a normal character which doesn't work as a delimiter.
     * 
     * Each element of the result array is trimmed automatically.
     * 
     * @param text the target
     * @return the result array.
     */
    static String[] splitText(String text, String delimiter) {

        if (text == null) {
            return new String[] {};
        }

        text = text.trim();

        if (text.equals("")) {
            return new String[] {};
        }

        List<String> list = new ArrayList<String>();
        String temp = "";
        boolean quote = false;
        for (int i = 0; i < text.length(); i++) {
            String ch = text.substring(i, i + 1);

            if (ch.equals("\"")) {
                quote = !quote;
                temp += ch;
            } else if (!quote && ch.equals(delimiter)) {
                list.add(temp.trim());
                temp = "";
            } else {
                temp += ch;
            }
        }
        list.add(temp.trim());

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

Related

  1. splitString(String str, String delimiter)
  2. splitString(String str, String delims)
  3. splitString(String toSplit, String delimiter)
  4. splitStringList(String strList, String delimit)
  5. splitStringUsingDelimiter(String name, String delimiter)
  6. splitToArray(String stringToSplit, String delimitter, boolean trim)
  7. splitToken(String str, String delimiter)
  8. splitToList(final String string, final String delim, final int limit)
  9. splitToList(String a_text, String a_delimiter)