Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

public class Main {
    /**
     * <p>Parses the specified {@link String} <code>str</code> with the given
     * delimiter <code>delim</code> and returns an array of {@link String}
     * delimited by the said delimiter. Note that this method takes into
     * account characters escaped by a backslash.</p>
     *
     * @param str
     * @param delim
     * @return {@link String}[]
     */
    public static String[] parseStringWithEscappedDelimiter(String str, char delim) {
        int i = 0;
        int state = 0;
        char c;
        int prev = 0;
        boolean firstTime = true;
        char[] testStringarr = str.toCharArray();
        List<String> strList = new ArrayList<String>(5);

        for (int len = testStringarr.length; i < len; i++) {
            c = testStringarr[i];

            if (state == 0) {
                if (c == '\\') {
                    state++;
                } else if (c == delim) {
                    if (firstTime) {
                        strList.add(str.substring(prev, i));
                    } else {
                        strList.add(str.substring(prev + 1, i));
                    }

                    if (prev == 0) {
                        firstTime = false;
                    }

                    prev = i;
                }
            } else {
                state--;
            }
        }

        if (firstTime) {
            strList.add(str.substring(prev));
        } else {
            strList.add(str.substring(prev + 1));
        }

        return strList.toArray(new String[strList.size()]);
    }
}