Java CSV String Split splitCSV(String str)

Here you can find the source of splitCSV(String str)

Description

split CSV

License

Mozilla Public License

Declaration

public static String[] splitCSV(String str) 

Method Source Code

//package com.java2s;
//License from project: Mozilla Public License 

public class Main {
    public static String[] splitCSV(String str) {
        java.util.ArrayList<String> DynStrs = new java.util.ArrayList<String>();
        //Current char
        char ch;//from   ww w .j av  a  2s.c  o m
        //Most recent split
        int lastbreak = 0;
        //Temp string (unneeded but makes code more readable IMO
        String temp;
        //Loops through the string
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            //If there's a quote
            if (ch == 34) {
                //If that quote is followed by a second quote
                if (str.charAt(i + 1) == 34) {
                    //Add a substring including quotes within quotes
                    temp = str.substring(i + 1, (str.indexOf('"', i + 2)));
                    DynStrs.add(temp);
                    lastbreak = str.indexOf('"', i + 2) + 2;
                    i = str.indexOf('"', (i + 2)) + 1;
                } else
                    //otherwise add a substring without quotes
                    temp = str.substring(i + 1, (str.lastIndexOf('"')));
                DynStrs.add(temp);
                lastbreak = str.lastIndexOf('"') + 2;
                i = str.lastIndexOf('"') + 1;
            } //if current char is a "
            else if (ch == 44) {
                temp = str.substring(lastbreak, i);
                if (lastbreak - i != 0)
                    DynStrs.add(temp);
                lastbreak = i + 1;
            } //if current char is a ,
        } //end string parsing
        DynStrs.add(str.substring(lastbreak));
        DynStrs.trimToSize();
        String[] result = new String[DynStrs.size()];
        DynStrs.toArray(result);
        return result;
    }
}

Related

  1. getContentsFromNumpyCSVString( String numpyString)
  2. getCsvValues(String line)
  3. getValuesFromCSVString(String csvString)
  4. SplitCSV(String csv)
  5. splitCSV(String inputString)
  6. splitCSV(String str)
  7. splitCSV(String str)
  8. splitCSV(String str, String delim)
  9. SplitCSVString(String str)