Java String Split by Line split(String line)

Here you can find the source of split(String line)

Description

This method splits a single CSV line into junks of String .

License

Apache License

Parameter

Parameter Description
line is the line to be split.

Return

An array of is returned.

Declaration

protected static String[] split(String line) 

Method Source Code

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

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**//w  w  w  . j av  a 2s . c om
     * This method splits a single CSV line into junks of {@link String}.
     * 
     * @param line
     *            is the line to be split.
     * @return An array of {@link String} is returned.
     */
    protected static String[] split(String line) {
        List<String> results = new ArrayList<>();
        StringBuffer buffer = new StringBuffer(line);
        while (buffer.length() > 0) {
            if (buffer.indexOf("\"") == 0) {
                int endIndex = buffer.indexOf("\"", 1);
                String result = buffer.substring(1, endIndex);
                results.add(result);
                buffer.delete(0, endIndex + 2);
            } else {
                int index = buffer.indexOf(",");
                if (index < 0) {
                    results.add(buffer.toString());
                    buffer.delete(0, buffer.length());
                } else {
                    String result = buffer.substring(0, index);
                    results.add(result);
                    buffer.delete(0, index + 1);
                }
            }
        }
        return results.toArray(new String[results.size()]);
    }
}

Related

  1. fastSplit(final String line, final char c)
  2. split(String aLine, char delimiter, char beginQuoteChar, char endQuoteChar, boolean retainQuotes, boolean trimTokens)
  3. split(String line)
  4. split(String line)
  5. split(String line)
  6. split(String line, char delimiter)
  7. split(String line, char delimiter)
  8. split(String line, String delimiter)
  9. split(String line, String regex)