split

今日からは、今までに自作したユーティリティ的なメソッドやクラスを載せていく。
自分の備忘録としてね。


今日は、String#split()もどき。
用途としては、引用符内の区切り文字を無視したいときに使う。
作ったきっかけは、コマンドラインアプリケーションでユーザーが入力した内容を配列にするためだったかな。
空白を含むフルパスなんか入力されると、普通のsplit()じゃ対応できないからね。
後々、csvのパースにも使うようになった。

public static String[] split(String text, char delimiter, char quote) {
    List ret = new ArrayList();
    String item = "";
    int quoteCount = 0;
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c == quote) {
            quoteCount++;
            item += c;
        } else if (c == delimiter) {
            if ((quoteCount % 2) == 0) {
                ret.add(trimQuote(item, quote));
                item = "";
            } else {
                item += c;
            }
        } else {
            item += c;
        }
    }
    if (item.length() > 0) {
        ret.add(trimQuote(item, quote));
    }
    return (String[])ret.toArray(new String[ret.size()]);
}

public static String trimQuote(String text, char quote) {
    if (text == null) {
        return null;
    }
    if (text.length() >= 2 && text.startsWith(String.valueOf(quote)) && text.endsWith(String.valueOf(quote))) {
        text = text.substring(1, text.length() - 1);
        text = text.replaceAll("\\" + quote + "\\" + quote, "\\" + quote);
    }
    return text;
}