Java CSV String Split toTable(String csv)

Here you can find the source of toTable(String csv)

Description

Convert a string in the csv format to a string table with the format [row][column]

License

Apache License

Parameter

Parameter Description
csv a parameter

Declaration

public static String[][] toTable(String csv) 

Method Source Code

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

import java.util.ArrayList;

public class Main {
    /**/*from   ww w.j a va 2 s  .  com*/
     * Convert a string in the csv format to a string table with the format [row][column]
     * @param csv
     * @return
     */
    public static String[][] toTable(String csv) {

        char escape = '\\';
        char string_sep = '\'';
        char column_sep = ',';

        char[] data = csv.toCharArray();
        String value = "";

        ArrayList<String> row = new ArrayList<String>();
        ArrayList<String[]> table = new ArrayList<String[]>();

        boolean inLine = false;
        int nColumns = 0;

        for (int i = 0; i < data.length; i++) {

            char c = data[i];

            // optimize this!!
            if (c == escape && !inLine || i == data.length - 1 || c == '\n') {

                if (i < data.length - 1 && data[i + 1] == 'n' || i == data.length - 1 || c == '\n') {

                    row.add(value);
                    value = "";

                    nColumns = Math.max(nColumns, row.size());
                    String[] row_array = row.toArray(new String[row.size()]);

                    table.add(row_array);
                    row.clear();

                }

            } else if (c == column_sep && !inLine) {

                row.add(value);
                value = "";

            } else if (c == string_sep) {
                inLine = !inLine;

            } else {
                value += c;
            }

        }

        String[][] result = new String[table.size()][nColumns];

        for (int r = 0; r < table.size(); r++) {

            String[] row_array = table.get(r);

            for (int c = 0; c < row_array.length; c++) {
                result[r][c] = row_array[c];
            }

        }

        return result;
    }
}

Related

  1. splitCSV(String str)
  2. splitCSV(String str)
  3. splitCSV(String str, String delim)
  4. SplitCSVString(String str)
  5. tokenizeCsv(String input)