Java String to Array stringToArray(final String data, final String delim)

Here you can find the source of stringToArray(final String data, final String delim)

Description

transforms a string list into an array of Strings.

License

Open Source License

Parameter

Parameter Description
data the string list.
delim the list delimiter.

Return

the array of strings.

Declaration

public static String[] stringToArray(final String data,
        final String delim) 

Method Source Code

//package com.java2s;
import java.util.ArrayList;

import java.util.List;

public class Main {
    /**/*from  w  w  w.  java  2s  .  c  o  m*/
     * transforms a string list into an array of Strings.
     * 
     * @param data
     *            the string list.
     * @param delim
     *            the list delimiter.
     * @return the array of strings.
     * @since 0.2
     */
    public static String[] stringToArray(final String data,
            final String delim) {

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

        final List tokens = new ArrayList(data.length() / 10);
        int pointer = 0;
        int quotePointer = 0;
        int tokenStart = 0;
        int nextDelimiter;
        while ((nextDelimiter = data.indexOf(delim, pointer)) > -1) {
            final int openingQuote = data.indexOf("\"", quotePointer);
            int closingQuote = data.indexOf("\"", openingQuote + 1);
            if (openingQuote > closingQuote) {
                throw new IllegalArgumentException(
                        "Missing closing quotation mark.");
            }
            if (openingQuote > -1 && openingQuote < nextDelimiter
                    && closingQuote < nextDelimiter) {
                quotePointer = ++closingQuote;
                continue;
            }
            if (openingQuote < nextDelimiter
                    && nextDelimiter < closingQuote) {
                pointer = ++closingQuote;
                continue;
            }
            // TODO: for performance, fold the trim into the splitting
            tokens.add(data.substring(tokenStart, nextDelimiter).trim());
            pointer = ++nextDelimiter;
            quotePointer = pointer;
            tokenStart = pointer;
        }
        tokens.add(data.substring(tokenStart).trim());
        return (String[]) tokens.toArray(new String[tokens.size()]);
    }
}

Related

  1. stringToArray(String charc, String commas)
  2. stringToArray(String inputVal, String delimiter)
  3. stringToArray(String s)
  4. stringToArray(String str, String separator)