Java String Split by Quote splitQuoted(String str, char delimiter)

Here you can find the source of splitQuoted(String str, char delimiter)

Description

split Quoted

License

Apache License

Declaration

public static List<String> splitQuoted(String str, char delimiter) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static List<String> splitQuoted(String str, char delimiter) {
        return splitQuoted(str, delimiter, false);
    }/*from w w  w .j  a  v a 2s .co m*/

    public static List<String> splitQuoted(String str, char delimiter, boolean skipEmpty) {
        List<String> tokens = new ArrayList<String>();

        if (isBlank(str))
            return tokens;

        StringBuffer sb = new StringBuffer(str);

        int start = 0, ch;
        boolean quoted = false;

        for (int i = 0; i < sb.length(); i++) {
            ch = sb.charAt(i);

            if (ch == '"') {
                quoted = !quoted;
                continue;
            }

            if (quoted)
                continue;

            if (ch == delimiter) {
                str = sb.substring(start, i).trim();

                if (!skipEmpty || str.length() > 0)
                    tokens.add(str);

                start = i + 1;
            }
        }

        str = sb.substring(start).trim();

        if (!skipEmpty || str.length() > 0)
            tokens.add(str);

        return tokens;
    }

    public static boolean isBlank(String value) {
        return value == null || value.trim().length() == 0;
    }

    public static String trim(String str, String trim) {
        int start = 0;

        while (str.startsWith(trim, start))
            start += trim.length();

        str = str.substring(start);

        while (str.endsWith(trim))
            str = str.substring(0, str.length() - trim.length());

        return str;
    }
}

Related

  1. splitIgoringQuotes(String str)
  2. splitOnCharWithQuoting(String s, char splitChar, char quoteChar, char escapeChar)
  3. splitOnCharWithQuoting(String s, char splitChar, char quoteChar, char escapeChar)
  4. splitOptions(String quotedOptionString)
  5. splitQuoted(String input, Character split)
  6. splitQuotedEscape(String src)
  7. splitQuotedStr(String str, char delimiter, char quote, boolean trim)
  8. splitQuotedString(String str)
  9. splitQuotedString(String str)