Java CSV String Split SplitCSVString(String str)

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

Description

Split CSV String

License

Apache License

Declaration

static String[] SplitCSVString(String str) 

Method Source Code

//package com.java2s;
/*/*from ww  w . j  a v  a  2s. c o  m*/
 * Copyright 2004-2007 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import java.util.ArrayList;

public class Main {
    static String[] SplitCSVString(String str) {
        if (str == null) {
            return new String[0];
        }

        int pos;
        int len;
        int last;
        char ch;
        boolean quot;
        ArrayList splitted;

        pos = 0;
        len = str.length();
        last = 0;
        ch = 0;
        quot = false;
        splitted = new ArrayList();

        while (pos < len) {
            ch = str.charAt(pos);

            if (!quot && ch == ',') {
                addStringToArrayList(last, pos, splitted, str);
                last = pos + 1;
            } else if (ch == '"') {
                quot = !quot;
            }
            pos += 1;
        }
        if (ch == ',') {
            splitted.add("");
        } else {
            addStringToArrayList(last, pos, splitted, str);
        }
        return (String[]) splitted.toArray(new String[0]);
    }

    private static void addStringToArrayList(final int last, final int pos, final ArrayList splitted,
            final String str) {
        String val = str.substring(last, pos);
        if ((val.length() > 0) && (val.charAt(0) == '\"') && (val.charAt(val.length() - 1) == '\"')) {
            val = val.substring(1, val.length() - 1);
        }
        splitted.add(val);
    }
}

Related

  1. splitCSV(String inputString)
  2. splitCSV(String str)
  3. splitCSV(String str)
  4. splitCSV(String str)
  5. splitCSV(String str, String delim)
  6. tokenizeCsv(String input)
  7. toTable(String csv)