Java String Split by Line splitCommaSeparated(String line)

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

Description

split Comma Separated

License

Open Source License

Declaration

public static String[] splitCommaSeparated(String line) 

Method Source Code

//package com.java2s;

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static String[] splitCommaSeparated(String line) {
        // items are separated by ','
        // each item is of the form abc...
        // or "..." (required if a comma or quote is contained)
        // " in a field is represented by ""
        List<String> result = new ArrayList<String>();
        StringBuilder item = new StringBuilder();
        boolean inQuote = false;
        for (int i = 0; i < line.length(); ++i) {
            char ch = line.charAt(i); // don't worry about supplementaries
            switch (ch) {
            case '"':
                inQuote = !inQuote;/*from  w ww .  j  ava  2  s  .  c  o m*/
                // at start or end, that's enough
                // if get a quote when we are not in a quote, and not at start, then add it and return to inQuote
                if (inQuote && item.length() != 0) {
                    item.append('"');
                    inQuote = true;
                }
                break;
            case ',':
                if (!inQuote) {
                    result.add(item.toString());
                    item.setLength(0);
                } else {
                    item.append(ch);
                }
                break;
            default:
                item.append(ch);
                break;
            }
        }
        result.add(item.toString());
        return result.toArray(new String[result.size()]);
    }
}

Related

  1. splitByBrackets(String line)
  2. splitBySeparator(String line, char sep)
  3. splitBySeparatorAndParen(String line, char sep)
  4. splitBySeparatorQuoteAndParen(String line, char sep)
  5. splitCommandLine(String str, boolean extract)
  6. splitHiddenNewLine(String s)
  7. splitInt(String line, String seperator, int def)
  8. splitIntoLines(String str)
  9. splitIntoNonEmptyLines(String s)